A compound literal is a postfix expression that provides an unnamed object whose value is given by the initializer list. The expressions in the initializer list may be constants. The C99 language feature allows compound constants in initializers and expressions, providing a way to specify constants of aggregate or union type. When an instance of one of these types is used only once, a compound literal eliminates the necessity of temporary variables. C++ supports this feature as an extension to Standard C++ for compatibility with C.
The syntax for a compound literal resembles that of a cast expression. However, a compound literal is an lvalue, while the result of a cast expression is not. Furthermore, a cast can only convert to scalar types or void, whereas a compound literal results in an object of the specified type. The syntax is as follows:
>>-(--type_name--)--{--+-initializer_list----+--}-------------->< '-initializer_list--,-'
If the type is an array of unknown size, the size is determined by the initializer list.
A compound literal has static storage duration if it occurs outside the body of a function and the initializer list consists of constant expressions. Otherwise, it has automatic storage duration associated with the enclosing block. The following expressions have different meanings. The compound literals have automatic storage duration when they occur within the body of a function.:
"string" /* an array of char with static storage duration */ (char[]){"string"} /* modifiable */ (const char[]){"string"} /* not modifiable */
A const-qualified compound literal can be placed in read-only memory. Compound literals with const-qualified types can share storage with string literals with the same or overlapping representations. For example,
(const char[]){"string"} == "string"
might yield 1 if the storage is shared. However, compound literals with const-qualified types are not necessarily shared. The following expressions result in two distinct objects of type struct s.
(const struct s){1,2,3} (const struct s){1,2,3}
Compound literals having vector type follow the same semantic rules as
regular compound literals:
vector unsigned int v1 = (vector unsigned int) {1,2,3,4};A compound literal is not a constant expression and therefore cannot be used to initialize a static variable. However, for compatibility with GNU C/C++, a static variable having vector type can be initialized with a compound literal of the same vector type, provided that all the initializers in the initializer list are constant expressions.
Related References