额外的反斜杠字符不会影响我的程序。为什么?

时间:2012-10-15 20:15:43

标签: c++ gcc g++ backslash

这段代码可以正常使用g ++运行。 我不是没有原因。它应该给出一个错误。

#include <iostream>
using namespace std;
int main(){
    int x=9;
    int y=6;
    //note that there is extra backslash in the end of if statement
    if(x==y)\
    {
        cout<<"x=y"<<endl;
    }
    //note that there is extra backslash in the end of if statement
    if(x!=y)\
    {
        cout<<"x!=y"<<endl;
    }
    return 0;
}

2 个答案:

答案 0 :(得分:19)

来自C ++标准:

  

(C ++ 11,2.2p1)“删除一个反斜杠字符(\)后面紧跟一个新行字符的每个实例,拼接物理源代码行以形成逻辑源代码行。只有任何物理上的最后一个反斜杠源线有资格成为这种拼接的一部分。“

C完全相同:

  

(C11,5.1.1.2翻译阶段p1)“每个反斜杠字符(\)的实例后面紧跟一个新行字符被删除,拼接物理   源代码行以形成逻辑源代码行。“

所以:

if(x==y)\
{
    cout<<"x=y"<<endl;
}

实际上相当于:

if(x==y){
    cout<<"x=y"<<endl;
}

答案 1 :(得分:6)

\转义换行符。 g++会在一行读取if(x==y){,这不是语法错误。