Isn't there a syntax error? Should printf(“one” “, two and ” “%s.\\n”, “three” ); be valid code?

折月煮酒 提交于 2019-11-28 12:56:16

This is standard behavior, adjacent string literals are concatenated together if we look at the C99 draft standard section 5.1.1.2 Translation phases paragraph 6 says:

Adjacent string literal tokens are concatenated

gcc does have many non-standard extensions, but if you build using -pedantic then gcc should warn you if it is doing something non-standard, you can read more in the documents section Extensions to the C Language Family.

The rationale is covered in the Rationale for International Standard—Programming Languages—C and it says in section 6.4.5 String literals:

A string can be continued across multiple lines by using the backslash–newline line continuation, but this requires that the continuation of the string start in the first position of the next line. To permit more flexible layout, and to solve some preprocessing problems (see §6.10.3), the C89 Committee introduced string literal concatenation. Two string literals in a row are pasted together, with no null character in the middle, to make one combined string literal. This addition to the C language allows a programmer to extend a string literal beyond the end of a physical line without having to use the backslash–newline mechanism and thereby destroying the indentation scheme of the program. An explicit concatenation operator was not introduced because the concatenation is a lexical construct rather than a run-time operation.

You had not got any error because there was/is Nothing wrong.

Two string "A""B" are concatenated. This is convention of language C.

Try gcc -E to display the preprocessed source code. You will have something like this:

int main()
{
    const char THREE[6] = "three";
    printf("one" ", two and" "%s.\n", THREE );
    return 0;
}

Then, follow the correct answer from @shafik-yaghmour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!