Table of Contents

C compound literals

C compound literals (C99) create anonymous temporary objects with specified values: (Type){...}. Use them to pass structs to functions without named variables, or initialize data in expressions.

Use compound literals for convenient inline struct/array passing without temporary variables.

Example

// compile: gcc -std=c99 -o compound compound.c
// run: ./compound
// description: compound literals for inline objects
 
#include <stdio.h>
 
typedef struct {
    int x;
    int y;
} Point;
 
void print_point(Point p) {
    printf("Point: (%d, %d)\n", p.x, p.y);
}
 
int main() {
    // Create inline struct without variable
    print_point((Point){10, 20});
    print_point((Point){.x = 30, .y = 40});
 
    // Array compound literal
    int *arr = (int[]){1, 2, 3, 4, 5};
    printf("Array: %d %d %d\n", arr[0], arr[1], arr[2]);
 
    // String literal (already compound-like)
    const char *str = (const char []){"Hello"};
    printf("String: %s\n", str);
 
    return 0;
}

Common patterns

Syntax:

Use cases:

Scope and lifetime:

Performance:

With designators:

Limitations: