12

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Robert Deml
  • 12,390
  • 20
  • 65
  • 92

4 Answers4

12

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

Andrew Aylett
  • 39,182
  • 5
  • 68
  • 95
1

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.

Nick
  • 5,875
  • 1
  • 27
  • 38
  • That was a bad example on my part. I was trying to strip all of my project-specific details out and came up with this example. – Robert Deml Feb 23 '10 at 15:56
  • 2
    Not strictly true: you can do boolean operations and there are some function-like calls (`defined()`). Some preprocessors allow a shed-load of extra stuff (I've seen people asking for log operators in the preprocessor, because they'd used them with an embedded compiler). – Andrew Aylett Feb 23 '10 at 16:01
-3

just use ordinary if-else

if      (sizeof(x)==2)  {...}
else if (sizeof(x)==4)  {...}
else                    {...}

and compiler will optimize it in compile time...

-3

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 :)

cwap
  • 11,087
  • 8
  • 47
  • 61