Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading