Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the output of this code and why?

Tags:

c

comments

gcc

With the following code, what's the output of this code, and why?

#include <stdio.h>

int main() {
        printf("Hello world\n"); // \\
        printf("What's the meaning of this?");
        return 0;
}
like image 675
Josejulio Avatar asked Nov 28 '25 09:11

Josejulio


2 Answers

The backslash at the end of the 4th line is escaping the following new line so that they become one continuous line. And because we can see the // beginning a comment, the 5th line is commented out.

That is, your code is the equivalent of:

#include <stdio.h>

int main() {
        printf("Hello world\n"); // \printf("What's the meaning of this?");
        return 0;
}

The output is simply "Hello world" with a new line.

Edit: As Erik and pmg both said, this is true in C99 but not C89. Credit where credit is due.

It is defined in the 2nd phase of translation (ISO/IEC 9899:1999 §5.1.1.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.

like image 173
Joseph Mansfield Avatar answered Nov 29 '25 21:11

Joseph Mansfield


It's "Hello world\n". Didn't you try? Line continuation (and e.g trigraphs) are well documented, look it up. A syntax highlighting editor (e.g. Visual Studio with VA X) will make this obvious.

Note that this works in C99 and C++ - not C89

like image 28
Erik Avatar answered Nov 29 '25 22:11

Erik