This compiles without warnings using clang.
typedef struct {
int option;
int value;
} someType;
someType *init(someType *ptr) {
*ptr = (someType) {
.option = ptr->option | ANOTHEROPT,
.value = 1
};
return ptr;
}
int main()
{
someType *typePtr = init( &(someType) {
.option = SOMEOPT
});
// do something else with typePtr
}
Is this even valid C?
If so: What is the lifetime of the compound literal?
It's valid C in C99 or above.
In your example, the compound literal has automatic storage, which means, its lifetime is within its block, i.e, the
main()
function that it's in.Recommended reading from @Shafik Yaghmour:
Yu Hao has answered with the standard, now some vulgarization.
Whenever you see a compound literal like:
you can replace it with:
So: