Why can't I use sizeof() in a #if? [duplicate]
I have this:
#if sizeof(int)
#error Can't use sizeof in a #if
#endif
I get this compiler error:
missing binary operator before token "("
Why can't I use the sizeof operator here?
Because sizeof() is calculated after the preprocessor is run, so the information is not available for #if
.
C compilers are logically split into two phases, even if most modern compilers don't separate them. First, the source is preprocessed. This involves working out and substituting all the preprocessor conditionals (#if, #define, replacing defined words with their replacements). The source is then passed, processed, to the compiler itself. The preprocessor is only minimally aware of the structure of C, it has no type knowledge, so it can't handle compiler-level constructs like sizeof().
Because you can only use literal constants in a preprocessor directive. Besides, sizeof(int) is always larger than 0, so I believe this #if would be true all the time anyway.
Consider:
#if sizeof(MyClass) > 3
#define MY_CONSTRAINT 2
#endif
class MyClass
{
#if MY_CONSTRAINT == 3
int myMember = 3;
#endif
};
Now, this is prolly not written in the correct syntax as it's been a while since the last time I did C++, but the point still stands :)
just use ordinary if-else
if (sizeof(x)==2) {...}
else if (sizeof(x)==4) {...}
else {...}
and compiler will optimize it in compile time...
精彩评论