开发者

Are string literals necessarily considered adjacent (and thus concatenated) when separated by a newline?

This is, I believe, a pedantic question. However since the FAQ d开发者_开发知识库oes not seem to disallow pedantry I'll go ahead and ask since I am genuinely interested in the answer.

I'm trying to read and understand (most of) the C99 standard (ISO/IEC 9899:1999). I'm basically wondering whether this is strictly conforming code:

printf("String literal 1 "
"String literal 2.\n");

Or should the newline be escaped like this:

printf("String literal 1 "\
"String literal 2.\n");

The relevant section of the standard seems to be section 5.1.1.2, which describes the translation phases. In phase 2 each "\" followed by a newline is deleted, splicing the lines into one line. Then in phase 6, adjacent string literal tokens are concatenated.

So for the first code sample to be conforming I see two options: Either string literals separated by a newline are considered adjacent, or the newline characters are removed in one of the previous translation phases.

So does anyone know if the first code sample above can be considered strictly conforming in this context, and if so is there something in the standard that makes this absolutely clear?


I believe they are both strictly conforming. The \ is a different feature than string literal concatenation. So your first example is definitely fine: there is a new line character between the literals, which is a white space, and thus forms a "sequence of white-space characters" as mentioned in 5.1.1.3.

The C standard in 5.1.1.2 is a bit unclear regarding the \ though, as it vaguely suggests that the new line character is removed as well as the backslash. But in this particular case it shouldn't matter whether there are white space characters between the string literals or not, I believe that your first example will be interpreted as

"String literal 1 ""String literal 2.\n"

which in turn results in the expected output.


Yes, a newline is just whitespace. So your first example is equivalent to

printf("String literal 1 " "String literal 2.\n");.


I cannot prove it with paragraphs of the standard, but the two alternatives are equivalent.

The newline is not part of the strings and so doesn't affect them.


To answer formally to your last question, yes, and you are pointing to the right paragraph in the standard.

Now, why not using a backslash as in the second code snippet? It is just useless!

The backslash+EOL is relevant only in a very few cases, e.g. when defining a macro on several lines while keeping a clear indentation (and I cannot think of any other cases). You could actually put backslash at the end of all the lines, it will compile without problem if you use a normal indentation. You could even put backslash+EOL between all the characters of your file! printf("..."); like this is perfectly valid :

p\
r\
in\
t\
f\
("..\
.")\
;`
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜