Saturday, December 10, 2022

[FIXED] Why printf statement don't continue to next lines?

Issue

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.

                                              .

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


Answered By - Andreas Wenzel
Answer Checked By - Robin (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.