开发者

C: long long always 64 bit?

If i'm using long longs in my code, can i a开发者_如何转开发bsolutely 100% guarantee that they will have 64 bits no matter what machine the code is run on?


No, C99 standard says that it will have at least 64 bits. So it could be more than that at some point I guess. You could use int64_t type if you need 64bits always assuming you have stdint.h available (standard in C99).

#include <stdint.h>
int64_t your_i64;


You can test if your compiler is C99 complying with respect to 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 since all unsigned values (in the preprocessor) are required to be the same type as uintmax_t and so 0U is of type uintmax_t and ~0U, 0U-1 and -1U all are the maximum representable number.

If this test works, chances are high that unsigned long long is in fact uintmax_t.

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

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

This does the same sort of trick but uses the postfix ULL to be sure to have constants of type unsigned long long.


They are guaranteed to be a minimnum of 64 bits. It's theoretically possible that they could be larger (e.g., 128 bits) though I'm reasonably they're only 64 bits on anything currently available.


With

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

or some equivalent.

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

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

Something like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜