Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 i.e

string1string2

Is this valid C?

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

like image 314
binW Avatar asked Sep 05 '25 02:09

binW


2 Answers

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.

like image 124
CB Bailey Avatar answered Sep 07 '25 20:09

CB Bailey


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"
);
like image 37
Ferruccio Avatar answered Sep 07 '25 20:09

Ferruccio