Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top