16

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
felix0322
  • 305
  • 2
  • 6

2 Answers2

20

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
  • 6,181
  • 3
  • 30
  • 38
  • 1
    Actually preprocessing happens during compilation, just in one of the earlier phases. Evaluating `sizeof` happens in a later phase. – sbi Oct 23 '09 at 11:14
  • 5
    @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 Oct 23 '09 at 12:43
  • 1
    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 Oct 23 '09 at 21:34
  • I could have sworn I've seen it work before. Maybe I'm mistaken though. – flarn2006 Sep 06 '20 at 14:21
11

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
  • 103,016
  • 27
  • 158
  • 194
  • 1
    "==" is also a operator. The answer from RichN point the problem a bit clearer for me. – felix0322 Oct 23 '09 at 10:52
  • 4
    @felix0322: The preprocessor has its own `==` operator, which is the one used in preprocessor directives. – sbi Oct 23 '09 at 11:15