FSMaxB FSMaxB - 1 month ago 8
C Question

C89 determine size of int at preprocessor time

I want to compile code conditionally depending on the size of an integer, but I didn't quite find a way to determine the size of an integer in the preprocessor stage.

One idea is using the

INT_MAX
and comparing it to a constant:

#if INT_MAX >= 9223372036854775807UL
printf("64 bit\n");
#elif INT_MAX >= 2147483647UL
printf("32 bit\n");
#else
printf("16 bit\n");
#endif


But I don't think it is guaranteed that a
UL
literal can be that large. And
ULL
is not available in C89 as far as I know.

So do you have any suggestions on how to solve this problem. Is there a macro that contains the size of int in some standard header maybe?

Answer

Testing the smaller values first should work, since the preprocessor uses shortcut evaluation on #if statements:

#if INT_MAX == 32767
    #error 16 bits
#elif INT_MAX == 2147483647
    #error 32 bits
#elif INT_MAX == 9223372036854775807
    #error 64 bits
#else
    #error "What kind of weird system are you on?"
#endif