Search code examples
cc-preprocessorsizeofansi-c

Conditional Compilation and compile time evaluation of expressions in ANSI C


I would like to do the following, but the compiler doesn't like it:

unsigned short foo = 1;
// do something with foo
#if sizeof(short) * CHAR_BIT > 16
   foo &= 0xffff;
#endif

I know this expression can always be fully evaluated at compile time, but maybe it's only evaluated after the preprocessor does it's thing? Is this possible in ANSI C or do I just have to do the check at run time?


Solution

  • You can't use sizeof in a preprocessor expression. You might want to do something like this instead:

    #include <limits.h>
    
    #if SHRT_MAX > 32767
        /* do soemthing */
    #endif