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