Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

Compound literal

A compound literal exposes an unnamed object through a `(type){ initializers }` expression. Unlike a cast, it yields an lvalue; the object's lifetime depends on its scope and storage-class specifiers.

Version: C23; repository compiler flag, production runtime not attested

Syntax

(type-name){ initializer-list }
([storage-class-specifiers] type-name){ [initializer-list] } /* C23; square brackets denote optional parts; storage-class specifiers are subject to scope constraints */

A compound literal exposes an unnamed object as an lvalue rather than merely converting a value like a cast. It supports scalar, structure, union, and array types, but not variable-length arrays. An [] array's size is inferred from its initializers.

Without storage-class specifiers, the object has static storage duration at file scope and automatic storage duration in a block. In the latter case, it lives until the current execution of the enclosing block ends, not merely the expression. Do not return a pointer to it from the function.

C23 permits constexpr, static, register, and thread_local, subject to declaration constraints for the corresponding scope. These are not freely interchangeable options. For a constexpr compound literal, the object's value is fixed at translation time. If the object has automatic storage duration, it is initialized each time the literal is evaluated.

In the example, & takes the address of a modifiable structure, and .x and .y designate the initialized members. The object remains alive during printf.

Examples

#include <stdio.h>

struct Point { int x; int y; };

int main(void)
{
    struct Point *p = &(struct Point){ .x = 3, .y = 4 };
    p->x += 2;
    printf("%d %d\n", p->x, p->y);
    return 0;
}

Result

5 4

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources