开发者

Why can't I use sizeof() in a #if? [duplicate]

This question already has answers here: 开发者_JAVA技巧 Why can't I use sizeof in a preprocessor condition? (2 answers) Closed 9 years ago.

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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜