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 onl开发者_开发百科y 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?
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
If your aim is to stop compilation when a data type is the wrong size, the following technique is useful:
struct _check_type_sizes
{
int int_is_4_bytes[(sizeof(int) == 4) ? 1 : -1];
int short_is_2_bytes[(sizeof(short) == 2) ? 1 : -1];
};
(The sizeof() function is interpreted here by the compiler, not the preprocessor.)
The main disadvantage of this method is that the compiler error isn't very obvious. Make sure you write a very clear comment.
精彩评论