Assigning a 64-bit constant as
int64_t foo = 0x1234LL;
is not portable, because long long
isn't necessarily int64_t
. This post Which initializer is appropriate for an int64_t? discusses use of INT64_C()
macro from <stdint.h>
, but isn't it also possible to use static_cast
as
int64_t foo = static_cast<int64_t>(0x1234);
?
Which one should I prefer and why, or do both of them work well?
I have searched on the internet and on SO, but did not find any place where the static_cast
option is explored. I have also done tests using sizeof()
to confirm that it works in the simple cases.
Actually, long long
is guaranteed to be at least 64 bits by the C implementation limits header <climits>
. The minimum limit on the minimum and maximum values for an object of type long long
is given as:
LLONG_MIN -9223372036854775807 // −(2^63 − 1)
LLONG_MAX +9223372036854775807 // 2^63 − 1
This corresponds to a signed 64 bit integer. You cannot store such a range of values without at least 64 information bits.
So go ahead and use 0x1234LL
. In fact, you can just as much use no suffix, because the first of the following types that can fit the value will be chosen:
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
... | ... | ...