c - 为什么 C 在使用条件运算符时不允许连接字符串?

标签 c string syntax concatenation conditional-operator

下面的代码编译没有问题:

int main() {
    printf("Hi" "Bye");
}

但是,这不会编译:

int main() {
    int test = 0;
    printf("Hi" (test ? "Bye" : "Goodbye"));
}

这是什么原因?

最佳答案

根据 C11 标准,章节 §5.1.1.2,相邻字符串文字的串联:

Adjacent string literal tokens are concatenated.

发生在翻译阶段。另一方面:

printf("Hi" (test ? "Bye" : "Goodbye"));

涉及条件运算符,它在运行时 进行评估。因此,在编译时,在翻译阶段,不存在相邻的字符串文字,因此连接是不可能的。语法无效,因此由您的编译器报告。


为了详细说明为什么部分,在预处理阶段,相邻的字符串文字被连接起来并表示为单个字符串文字( token )。相应地分配存储空间,连接的字符串文字被视为单个实体(一个字符串文字)。

另一方面,在运行时连接的情况下,目的地应该有足够的内存来保存连接的字符串文字,否则,预期将无法实现em> 可以访问连接的输出。现在,对于字符串文字,它们已经在编译时分配了内存,无法扩展以适应任何更多传入输入附加到原始内容。换句话说,无法将连接的结果作为单个字符串文字 进行访问(呈现)。因此,这种构造本质上是不正确的。

仅供引用,对于运行时字符串(不是文字)连接,我们有库函数strcat()连接两个字符串。注意,描述中提到:

char *strcat(char * restrict s1,const char * restrict s2);

The strcat() function appends a copy of the string pointed to by s2 (including the terminating null character) to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1. [...]

所以,我们可以看到,s1 是一个string,而不是string literal。然而,由于 s2 的内容没有以任何方式改变,它很可能是一个字符串文字

关于c - 为什么 C 在使用条件运算符时不允许连接字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37259472/

相关文章:

c - 无法将文件中的字符串读取到数组中以最终进行排序

c - 为什么 wait4() 被 waitpid() 取代

java - 如何以与 bash 相同的方式解析命令行序列?

javascript - 将 Javascript 代码放入字符串中?

c - 错误 : variable "string" is not initialized

php - 用于位比较的二进制符号

syntax - OCaml 显式类型签名

C *[] 和 ** 之间的区别

c - 找到最小的 n 个整数

javascript - jquery 错误 : Syntax error, 无法识别的表达式