Reputation:
I am trying to get the number of value bits in size_t
to be used in the preprocessor directives. Perhaps there is a macro for this? In essence, I would like to achieve something akin to this code where SIZE_T_BITS
is a hypothetical macro for the sake of demonstration.
#if SIZE_T_BITS == 32
// code for 32 bit size_t
#elif SIZE_T_BITS == 64
// code for 64 bit size_t
#else
// code for other bit sizes of size_t
#endif
Upvotes: 2
Views: 1325
Reputation: 153468
size_t
is some unsigned type. Compare the max value to common candidates. The max value is certainly some 2SIZE_T_BITS - 1. The smallest SIZE_MAX
may be is 0xFFFF
.
#include <stdint.h>
#if (SIZE_MAX == 0xFFFF)
#define SIZE_T_BITS 16
#elif (SIZE_MAX == 0xFFFFFFFF)
#define SIZE_T_BITS 32
#elif (SIZE_MAX == 0xFFFFFFFFFFFFFFFF)
#define SIZE_T_BITS 64
#else
#error TBD code SIZE_T_BITS
#endif
Although size_t
may have paddings bits (this is rare), the about method reflects the number of value bits in size_t
. This could differ from the total bits.
Note: SIZE_MAX
is defined such that
Each instance of these macros shall be replaced by a constant expression suitable for use in
#if
preprocessing directives, and this expression shall have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. C11 §7.20.3 2
Upvotes: 6
Reputation: 27460
This will work for GCC, CLang and MSVC:
#if defined(__x86_64__) || defined(_IA64) || defined(__IA64__) || defined(_M_X64)
#define SIZE_T_BITS 64
#else
#define SIZE_T_BITS 32
Upvotes: -1