tags:

views:

118

answers:

4

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?

+3  A: 

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
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
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
+5  A: 

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
+1  A: 

The #if is a preprocessor directive.
sizeof() is a C operator.

At the time of the preprocessor (when the #if is handled), the C operators are not executed.

EDIT: sizeof() is generally calculated at runtime. However, most compilers can/will replace a sizeof(int) with a constant....but compilation still happens well after the preprocessor has run.

semiuseless
`sizeof` is not a library function, it is an operator.
avakar
Not strictly true: sizeof() is a language feature, not a library function. Apart from some C99-specific wizardry, it's evaluated at compile time.
Andrew Aylett
Thanks for the comment about sizeof being an operator....fixed my answer.
semiuseless
-1, except for VLAs, `sizeof` is computed at compile-time. It is in fact a constant expression and can used as such.
avakar
A: 

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