8

See following example:

$ cat foo.c
int main()
{
    char *p = "foo\\
bar";
    return 0;
}
$ gcc -E foo.c
# 1 "foo.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "foo.c"
int main()
{
    char *p = "foo\bar";

    return 0;
}
$

From my understanding the 2nd \ is escaped by the 1st \ so the 2nd \ should not be combined with the following <NEWLINE> to form the line continuation.

pynexj
  • 19,215
  • 5
  • 38
  • 56
  • If you want a newline in a c-string you must explicitly insert it using `'\n'`. โ€“ LPs Jan 09 '17 at 08:02
  • See http://stackoverflow.com/questions/12694838/defining-a-string-over-multiple-lines โ€“ pringi Jan 27 '17 at 14:31

2 Answers2

17

The rules are quite explicit in ISO/IEC 9899:2011 ยง5.1.1.2 Translation 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.

The character preceding the final backslash is not consulted. Phase 1 converts trigraphs into regular characters. That matters because ??/ is the trigraph for \.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
15

The preprocessor removes all occurrences of backslash-newline before even trying to tokenize the input; there is no escape mechanism for this. It's not limited to string literals either:

#inclu\
de <st\
dio.h>

int m\
ain(void) {
    /\
* yes, this is a comment */
    put\
s("Hello,\
 world!");
    return 0;
}

This is valid code.

Using \\ to get a single \ only applies to string and character literals and happens much later in processing.

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • It might be worth noting that having this step precede all the others makes it possible to mechanically translate code that contains long lines for use on systems whose maximum line length would otherwise be too short to accommodate it, without the translation utility having to examine anything in the source file beyond the placement of newlines (though when translating a file from a system that uses fixed-length records to a system with a shorter record length, code would need to ensure that it only added newlines in cases where the content of the original line exceeded the new maximum). โ€“ supercat Jan 09 '17 at 17:03