How to enter constants int64_t / uint64_t?

What I'm trying to do is define a constant equal to 2 ^ 30 (I can change it to something like 2 ^ 34, so I prefer to have a room for it larger than 32 bits).

Why is the following minimal (?) Example not compiling?

#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; } 
+6
source share
3 answers

(uint64_t 1) syntax. When casting, you can use either uint64_t(1) or (uint64_t) 1 . The commented example works because it follows the correct syntax for the cast, as it would:

 const uint64_t test = ((uint64_t)1) << 30; 

Change: Although this directly answers the question, look at the answer of Shafik Yagmur on how to correctly determine an integral constant with a certain size.

+5
source

You can use the macro:

 UINT64_C 

for defining 64-bit unsigned integers, the cstdint header provides macros for defining integer literals of certain sizes, we see that in section 18.4.1 Header Summary:

The header also defines numerous form macros:

and includes:

plus function type macros:

[U] INT {8 16 32 64 MAX} _C

We have to go back to the standard C99 project to find how they work, section 7.18.4.1 Macros for constants with a minimum width that state:

[...], if uint_least64_t is a name of type unsigned long long int, then UINT64_C (0x123) can expand to the integer constant 0x123ULL .

as the correct way to define a 64-bit integer constant expression. This, unfortunately, is not a cpprefernce document, but cplusplus.com documents this function for the cstdint header, as well as the cstdint link for stdint.h .

+26
source

The syntax you are looking for is:

 const uint64_t test = 1ULL << 30; 

Post-fix ULL used for unsigned whole letters that are at least 64 bits wide.

+10
source

All Articles