Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the C preprocessor strip comments or expand macros first? [duplicate]

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?

like image 528
Phil Miller Avatar asked Oct 02 '09 17:10

Phil Miller


1 Answers

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.

like image 97
Reed Copsey Avatar answered Oct 27 '22 20:10

Reed Copsey