使用预处理器宏插入单行注释

Inserting a one-line line comment with a preprocessor macro

是否可以使用预处理器宏(或魔术)模拟单行注释 (//)?例如,这可以用 gcc -std=c99 编译吗?

#define LINE_COMMENT() ???

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

没有。以下是标准的摘录,显示了 C 程序的翻译阶段:

  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.

如您所见,在宏展开之前删除了评论,因此宏无法展开为评论。

你显然可以定义一个带有参数并展开为空的宏,但它比注释稍微有点限制,因为它的参数必须只包含有效的预处理器标记字符(例如没有 @ 或不匹配引号)。对于一般评论目的不是很有用。

没有。注释在预处理器阶段处理。您可以使用 #if 指令进行选择性编译(不考虑注释),如:

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

这就是您可以使用 C/C++ 中有限的宏预处理器实现的所有魔法。