简体   繁体   中英

printf(“string1”“string2”) is this valid C?

I was trying to figure out something when I wrote this by a mistake

printf("string1""string2");

To my surprise it compiled and produced a concatenated string output ie

string1string2

Is this valid C?

I am using gcc version 4.4.1 (Ubuntu 4.4.1-4ubuntu9)

Yes it is. Consecutive string literals are concatenated early in the parsing of C.

6.4.5 / 4:

In translation phase 6, the multibyte character sequences specified by any sequence of adjacent character and wide string literal tokens are concatenated into a single multibyte character sequence. If any of the tokens are wide string literal tokens, the resulting multibyte character sequence is treated as a wide string literal; otherwise, it is treated as a character string literal.

Yes, and it can be very useful to concatenate string constants at compile-time.

#define VERSION "1.0"
#define COMPANY "Trivial Software"

printf("hello world: v. " VERSION " copyright (c) " COMPANY);

or

puts(
  "blah blah blah\n"
  "blah blah blah\n"
  "blah blah blah\n"
  "blah blah blah\n"
);

Yes, it is valid and has been part of the C language for a very long time (if not since the beginning). The concatenation is done at compile time.

As other said, yes, it is valid. I only wanted to add that it is really useful to input long strings that fill several lines. You don't have to mess with \\ to indicate the string continues, and don't wanting to add a carriage return too, so you just write:

"very long string "
"that continues over here"

(watch out the spaces at the end of each string, it is a common mistake. In this case, "string" and "that" would be joint.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM