Does the C preprocessor strip comments or expand macros first?

Phil Miller picture Phil Miller · Oct 2, 2009 · Viewed 27.4k times · Source

Consider this (horrible, terrible, no good, very bad) code structure:

#define foo(x) // commented out debugging code

// Misformatted to not obscure the point
if (a)
foo(a);
bar(a);

I've seen two compilers' preprocessors generate different results on this code:

if (a)
bar(a);

and

if (a)
;
bar(a);

Obviously, this is a bad thing for a portable code base.

My question: What is the preprocessor supposed to do with this? Elide comments first, or expand macros first?

Answer

Reed Copsey picture Reed Copsey · Oct 2, 2009

Unfortunately, the original ANSI C Specification specifically excludes any Preprocessor features in section 4 ("This specification describes only the C language. It makes no provision for either the library or the preprocessor.").

The C99 specification handles this explicity, though. The comments are replaced with a single space in the "translation phase", which happens prior to the Preprocessing directive parsing. (Section 6.10 for details).

VC++ and the GNU C Compiler both follow this paradigm - other compilers may not be compliant if they're older, but if it's C99 compliant, you should be safe.