This question already has an answer here:
/*
#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?
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.
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.
Yes, the preprocessor replaces comments before handling directives.
From section 5.1.1.2 (Translation phases) of the C99 standard:
Yes (in every sane universe).
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.
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
or using comments for preprocessor-level concatenation (with C compilers that didn't support
##
operator in macro definitions)None of such tricks are legal in standard C. None of them really work.