字符串文字和 const char[] 或 char[] 之间的区别

Difference between string literal and const char[], or char[]

假设我有这个 C 代码

f((char []){ "hello" });
f((const char []){ "hello" });
f("hello");

在所有三种情况下,hello 都被复制到函数中。 指向 char 数组第一个字符的指针被初始化为函数参数。

我知道在 C 中,字符串文字对应于 char [],而在 C++ 中,字符串文字对应于 const char [],但它会创建与 char [] 相同的代码还是const char []?

在 C 程序中,您能否将所有出现的 "string"(char []){ "string" } 交换并在汇编级别获得相同的结果?

我不能说会生成什么代码,但是根据 C 标准(6.5.2.5 复合文字)

7 String literals, and compound literals with const-qualified types, need not designate distinct objects.

还有一个例子

13 EXAMPLE 6 Like string literals, const-qualified compound literals can be placed into read-only memory and can even be shared. For example,

(const char []){"abc"} == "abc"

might yield 1 if the literals’ storage is shared.

正如您正确提到的那样,C 中的字符串文字具有非常量字符数组类型。但是,它们可能不会被修改。另一方面,可以修改不带限定符 const 的复合文字。这会影响生成的汇编代码。或者,如果将限定符 const 与复合文字一起使用,则结果类型不同于相应字符串文字的类型。所以这又会影响生成的汇编代码。

另一个区别是字符串文字在任何情况下都具有静态存储持续时间,但复合文字可以具有自动存储持续时间。这也会影响生成的汇编代码。