Search code examples
csplitformatstandardsmultiline

Multiline expression: How does c compilers treat newline?


I'm reading the introduction section of the K&R book on C. To see what code format generates errors, I tried splitting printf("hello world!"); into different lines, as shown below. The problem is, I don't know if my results are implementation-independent. I used the GCC compiler.

What do C standards say about multiline expression? How do compilers deal with them?

/*
    printf("hello wor
    ld!\n");
*/

/*
    printf("hello world!
    \n");
*/

    printf("hello world!\
    n");

/*
    printf("hello world!\n
    ");
*/

    printf("hello world!\n"
    );

    printf("hello world!\n")
    ;

The commented-out expressions generate errors, while the remaining ones do not.

The behavior of the third expression was unexpected. Usually " needs to be terminated on the same line but the third expression works.

Third expression:

    printf("hello world!\
    n");

Output to console:

hello world!    n

It seems like \ can be used to split a string into multiple lines, but the space before n"); is included as part of the string. Is this a standard rule?


Solution

  • C 2018 5.1.1.2

    118 2. 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 basically writing

        printf("hello world!\
        n");
    

    is identical to writing

        printf("hello world!    n");