两个字符串文字的连接如何工作? [英] How does concatenation of two string literals work?
问题描述
char* a="dsa" "qwe";
printf("%s", a);
输出: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.
这是如何工作的?
推荐答案
由 ISO C 标准定义,相邻的字符串字面量合并为一个.
It's defined by the ISO C standard, adjacent string literals are combined into a single one.
语言有点枯燥(毕竟是标准),但 C11
的 6.4.5 String literals
部分指出:
The language is a little dry (it is a standard after all) but section 6.4.5 String literals
of C11
states:
在翻译阶段 6,由任何相邻字符序列和相同前缀的宽字符串文字标记指定的多字节字符序列连接成单个多字节字符序列.
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.
这在同一标准的5.1.1.2 翻译阶段,第6点
中也提到过,虽然更简洁一点:
This is also mentioned in 5.1.1.2 Translation phases, point 6
of the same standard, though a little more succinctly:
连接相邻的字符串文字标记.
Adjacent string literal tokens are concatenated.
这基本上意味着 abc";def"
与 abcdef"
没有什么不同.
This basically means that "abc" "def"
is no different to "abcdef"
.
这对于制作长字符串同时仍然具有良好的格式通常很有用,例如:
It's often useful for making long strings while still having nice formatting, something like:
const 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 :-)";
这篇关于两个字符串文字的连接如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!