Should I use static_cast or INT64_C to assign a 64-bit constant portable?

Assigning a 64-bit constant as

int64_t foo = 0x1234LL;

      

doesn't carry over because it long long

doesn't have to int64_t

. This post What initializer is appropriate for int64_t? discusses the use of the INT64_C()

from macro <stdint.h>

, but can't you use it static_cast

like

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

      

?

Who should I prefer and why, or do they both work well?

I've searched the web and SO but couldn't find a place where the option is covered static_cast

. I also ran tests with help sizeof()

to confirm that it works in simple cases.

+3


source to share


1 answer


In fact, long long

at least 64 bits are guaranteed by the C implementation constraints header <climits>

. The minimum limit of minimum and maximum values ​​for an object of type long long

is specified 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, keep using 0x1234LL

. In fact, you can also omit the suffix, because the first of the following types will be selected that may match this value:

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
...    | ...               | ...

      

+6


source







All Articles