compound literals
Constructs an unnamed object of specified type in-place, used when a variable of array, struct, or union type would be needed only once.
Syntax
( type ) { initializer-list }
|
(since C99) | ||||||||
where
type | - | a type name specifying any complete object type or an array of unknown size, but not a VLA |
initializer-list | - | list of initializers suitable for initialization of an object of type |
Explanation
The compound literal expression constructs an unnamed object of the type specified by type and initializes it as specified by initializer-list.
The type of the compound literal is type (except when type is an array of unknown size; its size is deduced from the initializer-list as in array initialization).
The value category of a compound literal is lvalue (its address can be taken).
The unnamed object to which the compound literal evaluates has static storage duration if the compound literal occurs at file scope and automatic storage duration if the compound literal occurs at block scope (in which case the object's lifetime ends at the end of the enclosing block).
Notes
Compound literals of const-qualified character or wide character array types may share storage with string literals.
(const char []){"abc"} == "abc" // might be 1 or 0, implementation-defined
Each compound literal creates only a single object in its scope:
int f (void) { struct s {int i;} *p = 0, *q; int j = 0; again: q = p, p = &((struct s){ j++ }); if (j < 2) goto again; // note; if a loop were used, it would end scope here, // which would terminate the lifetime of the compound literal // leaving p as a dangling pointer return p == q && q->i == 1; // always returns 1 }
Because compound literals are unnamed, a compound literal cannot reference itself (a named struct can include a pointer to itself)
Although the syntax of a compound literal is similar to a cast, the important distinction is that a cast is a non-lvalue expression while a compound literal is an lvalue.