klu*_*utt 7 c gcc compound-literals lvalue
I was reading about compound literals, and I saw that they are l-values. So I suspected that you can assign them, so I did an experiment and I noticed that this compiles without warnings with gcc -Wall -Wextra -pedantic:
struct foo {
int x;
int y;
};
int main(void) {
(struct foo){0,0} = (struct foo){1,1};
}
Run Code Online (Sandbox Code Playgroud)
这让我感到困惑,因为我真的看不到任何可能有用的情况。当你会永远要分配什么到一个复合文字?
或者它是常见的未定义行为之一?因为它看起来很像修改字符串文字。使用与上述相同的参数编译时没有警告:
struct foo *ptr = &(struct foo){0,0};
*ptr = (struct foo){1, 1};
char *str = "Hello";
*str = 'X'; // Undefined behavior
Run Code Online (Sandbox Code Playgroud)
根据C 标准 6.4.5.7修改字符串是未定义行为
嗯,它可能没有用,但它是一种限制最少的。
由于非数组类型的非 const 限定复合文字是可修改的左值,并且可以将可修改的左值分配给您可以对可修改的左值执行的所有操作,因此您可以分配给复合文字。
相反的情况是,对于复合文字的左值无法执行的操作,您会有一些额外的情况。
我发现了一个可以工作的用例,它会产生左值,但它不会:
foo(&((struct baz){0} = bar()))
Run Code Online (Sandbox Code Playgroud)
这里bar返回 astruct baz作为值,并且foo需要一个指向诸如struct参数的指针。如果没有此功能,您将无法进行内联传递这样的值。