user1061392
user1061392

Reputation: 324

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;
}

Upvotes: 5

Views: 328

Answers (2)

ouah
ouah

Reputation: 145839

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;
}

Upvotes: 19

tomahh
tomahh

Reputation: 13661

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

Upvotes: 6

Related Questions