Home > Enterprise >  Why printf statement don't continue to next lines?
Why printf statement don't continue to next lines?

Time:11-05

Consider this program:

#include <stdio.h>

int main()
{
    int a;
    a = 16;
  
    printf("This is the first line
    this is the second line
    ");
}

Why does this program throw error? Why can't it compile successfully and show the output as:


This is the first line
this is the second line
|

the symbol '|' here denotes blinking cursor, which is to show that the cursor moved to next, implying that after the "second line" a '\n' character as appeared in STDOUT.

                                              .

CodePudding user response:

In ISO C, a string literal must be in a single line of code, unless there is a \ character immediately before the end of the line, like this:

#include <stdio.h>

int main()
{
    int a;
    a = 16;
  
    printf("This is the first line\
    this is the second line\
    ");
}

However, this will print the following:

This is the first line    this is the second line 

As you can see, the indentation is also being printed. This is not what you want.

What you can do is define several string literals next to each other, on separate lines, adding a \n escape sequence as necessary.

#include <stdio.h>

int main()
{
    int a;
    a = 16;
  
    printf(
        "This is the first line\n"
        "this is the second line\n"
    );
}

Adjacent string literals will be automatically merged in phase 6 of the translation process.

This program has the desired output:

This is the first line
this is the second line

CodePudding user response:

You need to put a \ character at the end of a C source code line to combine it with the next line:

    printf("This is the first line\
    this is the second line\
    ");

That will print:

This is the first line    this is the second line    ∎

(The marks the end of the output.)

To put actual newline characters in the string literal, the \n escape sequence may be used:

    printf("This is the first line\n\
    this is the second line\n\
    ");

That will print:

This is the first line↩
    this is the second line↩
    ∎

(The marks the end of the output. The marks the end of a line.)

To avoid the extra spaces at the start of the second and third lines, remove the spaces from the beginning of the continuation lines:

    printf("This is the first line\n\
this is the second line\n\
");

That will print:

This is the first line↩
this is the second line↩
∎

(The marks the end of the output. The marks the end of a line.)

It is neater to replace the use of the line continuation with string literal concatenation as follows:

    printf("This is the first line\n"
        "this is the second line\n");

That will print:

This is the first line↩
this is the second line↩
∎

(The marks the end of the output. The marks the end of a line.)

  • Related