C Reference ยท Types and Literals
Compound literals in C
Reference for C99 compound literals: create unnamed struct, union and array values inline with (type){...}, their lifetime, mutability and common uses.
A compound literal creates an unnamed object of a given type in the middle of an expression. You write the type in parentheses followed by a braced initializer list: (struct point){3, 4}. It is C99's way of saying "a struct value right here" without declaring a temporary variable first.
You can use compound literals for structs, unions and arrays, take their address, pass them to functions, and even modify them (unless the type is const). Combined with designated initializers they make call sites very readable.
struct point { int x, y; }; draw((struct point){ .x = 3, .y = 4 });
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
(type-name){ initializer-list }
(type-name){ initializer-list, } /* trailing comma allowed */
(storage-class type-name){ ... } /* C23: static, constexpr, register, thread_local */
| Part | Description |
|---|---|
type-name |
A struct, union, array or scalar type. For int[] the length comes from the list. |
initializer-list |
Same rules as a variable initializer, including designators. Missing members are zero. |
{} |
C23 allows an empty list to zero the object. |
Returns: an lvalue of the stated type. Its address can be taken.
Errors / undefined behavior: using the object after its lifetime ends is undefined behavior. Modifying a const-qualified compound literal is undefined as well.
Usage notes
- Lifetime is the enclosing block. At file scope the literal has static storage duration; inside a function it lives until the end of the block. Never return a pointer to one.
- C23 storage-class specifiers:
(static int[]){1, 2, 3}gives a literal that lives forever. Before C23 you got static storage only at file scope. - Identical constant literals may share storage, just like string literals, if they are
const. Do not compare their addresses. - Not a cast.
(int){5}is a compound literal of typeint, not a cast of. A cast has no braces. - Macro trouble: the commas inside braces split macro arguments. Wrap the whole literal in extra parentheses or use a variadic macro.
- C++ differences: compound literals are a GCC/Clang extension in C++, and temporaries there behave differently.
- Good for options structs (
run((struct opts){.fast = true})) and for passing small temporary arrays without a named variable.