views:

243

answers:

6
/*
#define FOO
*/

#ifdef FOO
#define BAR "pirate"
#else
#define BAR "ninja"
#endif

int main() { printf(BAR); getchar(); }

In this code FOO is not defined (Visual Studio 2008). I assume that comments are processed first, then preprocessor, and then code. Are comments always processed before the preprocessor? Is this part of a standard?

+6  A: 

I assume that comments are processed first, then preprocessor, and then code. Are comments always processed before the preprocessor?

Sort of -- part of the preprocessor's job is to remove comments. In this case, it doesn't care that you have the directive inside the comments; it's still removed just like any other comment.

John Feminella
+2  A: 

Yes (in every sane universe).

Nifle
+3  A: 

Some quick research indicates that comments are converted to whitespace by the preprocessor. So, it's all part of the same flow.

According to Wikipedia, comments are handled before preprocessor directives.

Sapph
+3  A: 

Yes, from the language standard point of view, comments are processed (replaced with spaces) before the preprocessor begins doing its work.

In practical implementations, processing of comments can be done by the same code (e.g. the same executable) that handles preprocessor directives and carries out macro substitution, but the result must be the same: comments have no effect on preprocessor proper.

In older and/or non-standard code sometimes one might see some tricks that rely on non-standard behavior involving implementation-specific comments vs. preprocessor relationships, like, for example, creation of comments using preprocessor directives

#define CONCAT(a, b) a##b
#define BEGIN_COMMENT CONCAT(/, *)
#define END_COMMENT CONCAT(*, /)

BEGIN_COMMENT
  This code is supposedly commented-out
END_COMMENT

or using comments for preprocessor-level concatenation (with C compilers that didn't support ## operator in macro definitions)

#define OLD_CONCAT(a, b) a/**/b

None of such tricks are legal in standard C. None of them really work.

AndreyT
+5  A: 

According to the C standard, there are 8 translation phases during translation (compilation) of a program. Each comment is replaced by a whitespace character in translation phase 3, whereas preprocessing directives are executed in phase 4.

Alok
+5  A: 

Yes, the preprocessor replaces comments before handling directives.

From section 5.1.1.2 (Translation phases) of the C99 standard:

3) The source file is decomposed into preprocessing tokens and sequences of white-space characters (including comments).... Each comment is replaced by one space character....

4) Preprocessing directives are executed, macro invocations are expanded, ....

jamesdlin