Defining and initializing compound literals

suggest change

A compound literal is an unnamed object created in the scope where it is defined. Compound literals were introduced in C99.

Examples from C11 6.5.2.5

int *p = (int [2]){ 2, 4 };

p is initialized to the address of the first element of an unnamed array of two ints.

The compound literal is an lvalue. The storage duration of the unnamed object is static if the literal appears at file scope, and automatic if it appears at block scope. In the latter case, the object's lifetime ends when control leaves the enclosing block.

void f(void)
{
    int *p;
    /* p must already point to a valid int. */
    p = (int [2]){ *p };
}

p is assigned the address of the first element of an array of two ints. The first element has the value previously pointed to by p, and the second is zero. If p does not already point to a valid int, evaluating *p is undefined behavior. The new array remains valid until the end of the block.

Compound literal with designators

(also from C11)

struct point {
  unsigned x;
  unsigned y;
};

extern void drawline(struct point, struct point);

// used somewhere like this
drawline((struct point){.x=1, .y=1}, (struct point){.x=3, .y=4});

A hypothetical function drawline receives two arguments of type struct point. The first has coordinate values x == 1 and y == 1, and the second has x == 3 and y == 4.

Compound literal without specifying array length

int *p = (int []){ 1, 2, 3};

The array length is not written explicitly, so it is determined by the initializer.

Compound literal having length of initializer less than array size specified

int *p = (int [10]){1, 2, 3};

The remaining elements are initialized to 0.

Read-only compound literal

A compound literal is an lvalue, so its elements can be modified unless it is const-qualified. A read-only compound literal can be written (const int[]){1, 2}.

Compound literal containing arbitrary expressions

Inside a function, a compound literal, as for any initialization since C99, can have arbitrary expressions.

void foo(void)
{
    int *p;
    int i = 2, j = 5;
    /*...*/
    p = (int [2]){ i+j, i*j };
    /*...*/
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents