Blender
Blender

Reputation: 298166

Inserting a one-line line comment with a preprocessor macro

Is it possible to simulate a one-line comment (//) using a preprocessor macro (or magic)? For example, can this compile with gcc -std=c99?

#define LINE_COMMENT() ???

int main() {
    LINE_COMMENT()  asd(*&#@)($*?><?><":}{)(@
    return 0;
}

Upvotes: 2

Views: 1647

Answers (2)

Alex Celeste
Alex Celeste

Reputation: 13370

No. Here is an extract from the standard showing the phases of translation of a C program:

  1. The source file is decomposed into preprocessing tokens and sequences of white-space characters (including comments). A source file shall not end in a partial preprocessing token or in a partial comment. Each comment is replaced by one space character. New-line characters are retained. Whether each nonempty sequence of white-space characters other than new-line is retained or replaced by one space character is implementation-defined.

  2. Preprocessing directives are executed, macro invocations are expanded, and _Pragma unary operator expressions are executed. If a character sequence that matches the syntax of a universal character name is produced by token concatenation (6.10.3.3), the behavior is undefined. A #include preprocessing directive causes the named header or source file to be processed from phase 1 through phase 4, recursively. All preprocessing directives are then deleted.

As you can see, comments are removed before macros are expanded, so a macro cannot expand into a comment.

You can obviously define a macro that takes an argument and expands to nothing, but it's slightly more restrictive than a comment, as its argument must consist only of valid preprocessor token characters (e.g. no @ or unmatched quotes). Not very useful for general commenting purposes.

Upvotes: 5

Luis Colorado
Luis Colorado

Reputation: 12668

No. Comments are processed at preprocessor phase. You can do selective compilation (without regard to comments) with #if directives, as in:

#if 0
...  // this stuff will not be compiled
...
#endif // up to here.

that's all the magic you can do with the limited macro preprocessor available in C/C++.

Upvotes: 1

Related Questions