3

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.

Community
  • 1
  • 1
Masked Man
  • 1
  • 7
  • 40
  • 80

1 Answers1

6

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
...    | ...               | ...
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • 1
    Thanks. What if long long is more than 64-bits, say 128-bits? I fail to recall what the standard says. Does assigning a larger type to a smaller type have well-defined behavior? (Of course, I am considering the case where the value fits within 64-bits.) – Masked Man Feb 10 '13 at 15:07
  • @Deidara-senpai In this case, where the destination type is signed, the result will be undefined if you try and fit a larger integer value in the `int64_t`. – Joseph Mansfield Feb 10 '13 at 15:21
  • Well, yes, I am aware of that, but if the value fits within 64-bits, then is the result well-defined? – Masked Man Feb 10 '13 at 15:23
  • 1
    @Deidara-senpai Maybe I'm confused, but of course, assigning a value that would fit in 64 bits to an `int64_t` will be perfectly fine. – Joseph Mansfield Feb 10 '13 at 15:26
  • Ok, thanks. I always have trouble remembering these things from the standard. – Masked Man Feb 10 '13 at 15:33