PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, December 10, 2022

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

 December 10, 2022     c, printf, semantics, syntax     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing