-->

How does concatenation of two string literals work

2019-01-02 21:03发布

问题:

char* a="dsa" "qwe";
printf("%s",a);

output: dsaqwe

My question is why does this thing work. If I give a space or nothing in between two string literals it concatenates the string literals.

How is this working?

回答1:

It's defined by the ISO C standard, adjacent string literals are combined into a single one.

The language is a little dry (it is a standard after all) but section 6.4.5 String literals of C11 states:

In translation phase 6, the multibyte character sequences specified by any sequence of adjacent character and identically-prefixed wide string literal tokens are concatenated into a single multibyte character sequence.

This is also mentioned in 5.1.1.2 Translation phases, point 6, a little more succinctly:

Adjacent string literal tokens are concatenated.

This basically means that "abc" "def" is no different to "abcdef".

It's often useful for making long strings while still having nice formatting:

char *myString = "This is a really long "
                 "string and I don't want "
                 "to make my lines in the "
                 "editor too long, because "
                 "I'm basically anal retentive :-)";


回答2:

You answered your own question.

If I give a space or nothing in between two string literals it concatenates the string literals.

That's one of the features of the C syntax.



回答3:

And to answer your unasked question, "What is this good for?"

For one thing, you can put constants in string literals. You can write

#define FIRST "John"
#define LAST "Doe"

const char* name = FIRST " " LAST;
const char* salutation = "Dear " FIRST ",";

and then if you'll need to change the name later, you'll only have to change it in one spot.
Things like that.



回答4:

ISO C standard §5.1.1.2 says:-

  1. Adjacent string literal tokens are concatenated.
  2. White-space characters separating tokens are no longer significant.


回答5:

I'm pretty sure this is a compiler feature.



标签: