c++ - clang:单行注释中用空格分隔的反斜杠和换行符

标签 c++ clang

为什么会这样(live):

int main()
{
    // my pretty comment /\   
    //
    // 


}

在 clang 上发出警告:

warning: backslash and newline separated by space [-Wbackslash-newline-escape]

看起来该代码完全有效,没有任何陷阱。

最佳答案

来自 C++14 草案 [4296] :

2.2 翻译阶段 [lex.phases]

  1. Each instance of a backslash character () immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice. Except for splices reverted in a raw string literal, if a splice results in a character sequence that matches the syntax of a universal-character-name, the behavior is undefined. A source file that is not empty and that does not end in a new-line character, or that ends in a new-line character immediately preceded by a backslash character before any such splicing takes place, shall be processed as if an additional new-line character were appended to the file.

它的第一句话就给了你警告。

在您的示例代码中:

int main()
{
    // my pretty comment /\
    int x;
    int y = x;    
}

int x; 行将被加入到上面行的注释中,并将在下一阶段的翻译中删除。所以你得到了一个错误:

error: use of undeclared identifier 'x'

但是

int main()
{
    // my pretty comment /\   
    //
}

有效并且不会导致错误。您可能会注意到,g++(不带-Wall)不会在此处发出警告。它看起来像无用的警告,但我认为编译器可能会将其视为新行字符转义的可能失败。因此,最好在这里向您发出警告。

Do we need this warning there ?

事实上,不,我们这里不需要它。但这只是一个诊断警告,有这样的警告能够发现可能的问题比根本没有更好。

我想,这还有一个原因,比如:

  1. 人们通常不会逃避空间。为什么? :)

  2. 对于多行注释,这里是 /**/ 序列。

关于c++ - clang:单行注释中用空格分隔的反斜杠和换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31673945/

相关文章:

c++ - 测量程序所用的时间

c++ - 将 cout 与 basic_string<unsigned char> 一起使用

clang - Clang是否有类似#pragma GCC目标的内容?

c++ - 了解链接器重复符号错误的根源

c - 如何检测预处理器中的 X32 ABI 或环境?

c++ - undefined symbol _EVP_PKEY_CTX_new_id

c++ - 功能参数生命周期

c++ - 使用|在 C++ 中进行声明时

c++ - 使用 inrange (OpenCV) 对 RGB 图像进行阈值处理

c++ - 不同命名空间中别名声明的成员特化