Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

c - Isn't there a syntax error? Should printf("one" ", two and " "%s. ", "three" ); be valid code?

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.
", THREE );
    return 0;
}

The printf is effectively:

printf("one" ", two and " "%s.
", "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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...