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

∥☆過路亽.° 提交于 2019-11-27 07:17:33

问题


Take a look at this code:

#include <stdio.h>

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

The printf is effectively:

printf("one" ", two and " "%s.\n", "three" );

and the output is:

one, two and three.

gcc gives neither error nor warning messages after compiling this code. Is the gcc compiler supposed work in that way, or is it a bug?


回答1:


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.




回答2:


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

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




回答3:


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



来源:https://stackoverflow.com/questions/20548200/isnt-there-a-syntax-error-should-printfone-two-and-s-n-three

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