Modern C (C11/C17/C23)

a compound literal

/ KOM-pound /

Sometimes you want a temporary struct or array right where you use it, without first declaring a named variable for it. A compound literal is exactly that: an unnamed object you create inline by writing a type in parentheses followed by a braced initializer, for example (struct point){ .x = 3, .y = 4 }. It gives you a ready-made object you can pass to a function or take the address of, on the spot.

The form is (type){ initializer-list }, and the braces accept the same designated-initializer syntax as a normal declaration. The result is an actual lvalue — it has an address, so &(int){5} is a valid pointer to an int holding 5. Its storage duration depends on where it appears: a compound literal written inside a function has AUTOMATIC storage, meaning it lives only until the end of the enclosing block, just like a local variable; one at file scope has static storage. This feature is from C99.

It matters for writing concise code: passing a temporary config struct to a function, building an array argument inline, or initializing a pointer to a small fixed object. The crucial caveat: because a block-scope compound literal dies at the end of its block, returning or storing a pointer to it for use later gives you a DANGLING pointer and undefined behavior — its lifetime is the block, not the program.

void draw(struct point p); draw((struct point){ .x = 3, .y = 4 }); // temporary, no named var int *q = &(int){ 42 }; // pointer to an inline int // ok inside this block; q dangles once the block ends

An inline unnamed object with a real address; inside a function it lives only to the end of its block.

A block-scope compound literal has automatic storage: keeping a pointer to it past the end of its block is a dangling pointer and undefined behavior.

Also called
anonymous object匿名物件型別轉換式初始化