C: is longest longest always 64 bit?

If I use long longs in my code, can I absolutely 100% guarantee that they will have 64 bits no matter what machine this code is running on?

+7
source share
4 answers

No, the C99 standard says it will have at least 64 bits. So, at some point it could be more. You can use the int64_t type if you need 64 bits, always assuming you have stdint.h (standard on C99).

 #include <stdint.h> int64_t your_i64; 
+14
source

You can check if your C99 compiler matches the numbers in the preprocessor with this

 # if (~0U < 18446744073709551615U) # error "this should be a large positive value, at least ULLONG_MAX >= 2^{64} - 1" # endif 

This works because all unsigned values ​​(in the preprocessor) must be of the same type as uintmax_t , and therefore 0U is of type uintmax_t and ~0U , 0U-1 and -1U all the maximum representable numbers.

If this test works, the chances are high that the unsigned long long is actually uintmax_t .

For correct expression after the preprocessing phase to test this with real do types

 unsigned long long has_ullong_max[-1 + 2*((0ULL - 1) >= 18446744073709551615ULL)]; 

This does the same trick, but uses the ULL postfix to have constants like unsigned long long .

+1
source

It is guaranteed that they will be minimum 64 bits. It is theoretically possible that they can be larger (for example, 128 bits), although it is reasonable that they are only 64 bits for everything that is currently available.

0
source

FROM

 #if CHAR_BIT * sizeof (long long) != 64 #pragma error "long long is not 64 bits" #endif 

or some equivalent.

Based on the comment: if you want to support compilers where sizeof cannot be used in the pre-processor, see this thread:

http://www.daniweb.com/forums/thread13553.html

Something like that:

  char longlongcheck[(sizeof(long long) * CHAR_BIT) == 64]; // won't compile if the expression is 0. 
0
source

All Articles