Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An extra backslash character do not effect my program. Why?

This code will work and run fine with g++. I do not no why. It should give an error.

#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;
}
like image 443
user1061392 Avatar asked Oct 15 '12 20:10

user1061392


2 Answers

From the C++ Standard:

(C++11, 2.2p1) "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."

C says exactly the same:

(C11, 5.1.1.2 Translatation phases p1) "Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines."

So:

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

is actually equivalent to:

if(x==y){
    cout<<"x=y"<<endl;
}
like image 135
ouah Avatar answered Oct 03 '22 16:10

ouah


\ escapes the newline. g++ will read if(x==y){ on one line, which is not a syntax error.

like image 30
tomahh Avatar answered Oct 03 '22 15:10

tomahh