c++ - 为什么成对注释不能放在 C++ 中的字符串中?

标签 c++

通常里面的任何东西/**/被视为评论。

但是声明, 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/

相关文章:

c++ - 使用 dynamic_pointer_cast 通过引用获取 shared_ptr

c++ - 带有子类的类的纯接口(interface)

c# - 从 C# 将 Bool 数组传递给 C++ 代码

c++ - 从 Visual Studio 解决方案生成 Make 文件(用于 GCC)

c++ - 如何使用原子头 C++

c++ - 编译器无法推断出 C++ 中的专用模板

c++ - 如何在 C++ 中将两个元组作为参数发送

c++ - iOS:在 Objective-C++ 中定义和使用 C++

c# - 从 C# 应用程序引用 c++ dll 需要做什么?

c++ - C++ 容器的迭代器失效规则