c – 我应该使用static_cast还是INT64_C来便携地分配64位常量?

将64位常量指定为

int64_t foo = 0x1234LL;

不可移植,因为long long不一定是int64_t.这篇文章Which initializer is appropriate for an int64_t?讨论了从< stdint.h>中使用INT64_C()宏,但是也不能使用static_cast作为

int64_t foo = static_cast<int64_t>(0x1234);

我应该选择哪一个,为什么,或者两者都运作良好?

我在互联网上搜索了SO,但没有找到任何探测static_cast选项的地方.我还使用sizeof()进行了测试,以确认它在简单的情况下有效.

解决方法:

实际上,C实现限制标题< climits>保证long long至少为64位. long long类型对象的最小值和最大值的最小限制为:

LLONG_MIN   -9223372036854775807 // −(2^63 − 1)
LLONG_MAX   +9223372036854775807 // 2^63 − 1

这对应于带符号的64位整数.如果没有至少64个信息位,则无法存储这样的值范围.

所以继续使用0x1234LL.实际上,您可以使用无后缀,因为将选择适合该值的以下第一种类型:

Suffix | Decimal constants | Octal or hexadecimal constant
-------|-------------------|------------------------------
none   | int               | int
       | long int          | unsigned int
       | long long int     | long int
       |                   | unsigned long int
       |                   | long long int
       |                   | unsigned long long int
...    | ...               | ...
上一篇:Python np.nonzero(ndarray) 返回数组中不为0的元素的索引


下一篇:在php5中,如何阻止GET从(错误地)转换为数字?