What I'm trying to do is to define a constant equal to 2^30 (I may change it to something like 2^34, so I prefer to have a room larger than 32 bits for it).
Why the following minimal(?) example doesn't compile?
#include <stdint.h>
// test.cpp:4:33: error: expected primary-expression before numeric constant
// test.cpp:4:33: error: expected ')' before numeric constant
const uint64_t test = (uint64_t 1) << 30;
//const uint64_t test1 = (uint64_t(1)) << 30;// this one magically compiles! why?
int main() { return 0; }
(uint64_t 1)
is not valid syntax. When casting, you can either useuint64_t(1)
or(uint64_t) 1
. The commented out example works because it follows the proper syntax for casting, as would:Edit: While this directly answers the question, see the answer by Shafik Yaghmour on how to properly define an integral constant with specific size.
The syntax you are looking for is:
The post-fix
ULL
is used for unsigned integer literals that are at least 64-bits wide.You can use the macro:
to define a 64bit unsigned integer literal, the
cstdint
header provides macros for defining integer literals of specific sizes, we see that in section18.4.1
Header synopsis:and includes:
We have to go back to the C99 draft standard to find how they work, section
7.18.4.1
Macros for minimum-width integer constants which says:as the proper way of defining a 64bit integer constant expression. This is unfortunately not document on cpprefernce but cplusplus.com does document this feature for of the
cstdint
header as well as the posix reference for stdint.h.