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};
}
It got me confused, because I really cannot see any situation at all where this could be useful. When would you ever want to assign anything to a compound literal?
Or is it one of the usual undefined behaviors? Because it looks very much alike modifying string literals. This compiles without warnings with the same parameters as above:
struct foo *ptr = &(struct foo){0,0};
*ptr = (struct foo){1, 1};
char *str = "Hello";
*str = 'X'; // Undefined behavior
Modifying the string is undefined behavior according to C standard 6.4.5.7
Well, it might not be useful, but it is the one that has least restrictions.
Since a non-const-qualified compound literal of non-array type is a modifiable lvalue, and modifiable lvalues can be assigned to among all things that you can do to modifiable lvalues, then you can assign to compound literals.
The opposite would be that you would have some extra cases for what you cannot do to lvalues that are compound literals.
I found out a use case for this that would work would assignment result in lvalue, which it doesn't:
Since you just a moment ago stated that yo do not like macros, then I am not sure if this is going to convince you, but this makes it possible to write a macro that expands to something likehere
barreturns astruct bazas a value, andfooneeds a pointer to suchstructas an argument. Without this feature you cannot do such value passing inline.