通常里面的任何东西/*
和 */
被视为评论。
但是声明,
std::cout << "not-a-comment /* comment */";
版画 not-a-comment /* comment */
而不是 not-a-comment
.
为什么会这样?在 C++ 中还有其他地方我不能使用注释吗?
最佳答案
这是最大咀嚼原则的结果。这是 C++ 语言遵循的词法规则。处理源文件时,翻译分为(逻辑)阶段。在第 3 阶段,我们得到预处理 token :
[lex.phases]
1.3 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.
将注释转换为空白 pp-token 是在同一阶段完成的。现在字符串文字是一个 pp-token:
[lex.pptoken]
preprocessing-token: header-name identifier pp-number character-literal user-defined-character-literal string-literal user-defined-string-literal preprocessing-op-or-punc each non-white-space character that cannot be one of the above
与其他文字一样。最大咀嚼原理告诉我们:
3 If the input stream has been parsed into preprocessing tokens up to a given character:
- Otherwise, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token, even if that would cause further lexical analysis to fail, except that a header-name is only formed within a #include directive.
因此,因为预处理找到了开头的 "
,它必须继续寻找最长的字符序列,这些字符将构成有效的 pp-token(在这种情况下,token 是一个字符串文字)。这序列在结束 "
处结束。这就是它不能停止和处理评论的原因,因为它有义务消耗到结束的引号。
按照这些规则,您可以查明评论不会被预处理器作为评论处理的地方。
关于c++ - 为什么成对注释不能放在 C++ 中的字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53911649/