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

Why printf statement don't continue to next lines?

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.

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

                                              .

>Solution :

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
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