Space ignored after backslash?

Viewed 411

I'm having difficulties understanding why compiling following program fails

// This is comment \ 
int main(void) {
        return 0;
}

Notice there is space (0x20) after the \ character. Compilation fails with

+   $ gcc test.c -std=c11 -pedantic
test.c:3:2: error: expected identifier or ‘(’ before ‘return’
    3 |  return 0;
      |  ^~~~~~
test.c:4:1: error: expected identifier or ‘(’ before ‘}’ token
    4 | }
      | ^

and I don't understand why. Reading the C11 standard (well, latest draft), section 5.1.1.2 point 2 states that (emphasis mine)

Each instance of a backslash character (\) immediately followed by a new-linecharacter 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 partof such a splice. A source file that is not empty shall end in a new-line character,which shall not be immediately preceded by a backslash character before any suchsplicing takes place.

What am I missing? Is this behaviour according to standard? gcc and clang both behave the same way (clang prints warning though). Can I rely on any conforming compiler behaving the same way?

1 Answers

The problem is that the newline is also escaped. When I try compiling on MacOS I get these warnings :

t.c:1:20: warning: backslash and newline separated by space
      [-Wbackslash-newline-escape]
// This is comment \
                   ^
t.c:1:21: warning: multi-line // comment [-Wcomment]
// This is comment \
                    ^

so this part :

int main(void) {

is also commented. You're left with

    return 0;
}

and the compiler doesn't even have time to reach the orphan }, it's shouting at the sight of a return statement outside a function.

Related