What's the output of this code and why?
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;
}
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.
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
The trailing backslash causes the next line to be 'spliced' to the line that ends inthe backslash - even if it's part of a comment. This is nearly always unintentional (unless it's a deliberate obfuscation trick), and will cause a bug unless the next line is entirely whitespace or a comment itself.
This happens because 'line-splicing' occurs in translation phase 2, while removing comments happens in phase 3.
Newer compilers will warn about the single-line comment being continued to the next line (I'm not sure exactly what warning level might be required though):
GCC 4.5.1 (MinGW)
C:\temp\test.c:4:34: warning: multi-line comment
MSVC 9 (VS 2008) or 10 (VS 2010):
C:\temp\test.c(5) : warning C4010: single-line comment contains line-continuation character
C:\temp\test.c:4:34: warning: multi-line comment
C:\temp\test.c(5) : warning C4010: single-line comment contains line-continuation character
精彩评论