views:

579

answers:

2

I understand that sizeof is an operator, which is evaluated at compile time to an integer constant. But it seem it can not be used in the #if preprocessor directive like:

#if 4 == sizeof(int)
    typedef int Int32;
#endif

(cygwin-gcc 3.4.4 as well as Visual C++ 6.0 report compile errors)

Why is such usage not allowed?

+11  A: 

Because sizeof is evaluated at compilation time while directives are evaluated before compilation, and the part that does that is not the compiler, so it won't understand what sizeof means.

RichN
Actually preprocessing happens during compilation, just in one of the earlier phases. Evaluating `sizeof` happens in a later phase.
sbi
@sbi Preprocessing isn't a part of compilation - compiler usually runs preprocessor before the actual compilation, but you can instruct compiler not to do so. RichN's answer is 100% correct.
qrdl
Well, I was wrong, but only in terminology: It's one of the phases of _translation_. According to this http://stackoverflow.com/questions/1476892/1479972#1479972, there's no phase called "compilation" either, so what's meant with that seems open to interpretation.
sbi
+7  A: 

The sizeof is a C operator. You can't use C code in preprocessor directives. Preprocessor directives are evaluated before the compilation takes place.

kgiannakakis
You got their first!
Chris Huang-Leaver
"==" is also a operator. The answer from RichN point the problem a bit clearer for me.
felix0322
@felix0322: The preprocessor has its own `==` operator, which is the one used in preprocessor directives.
sbi