c-compound-literals
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:
(Type){initializer}for structs(Type[]){values}for arrays(Type[size]){values}with explicit size
Use cases:
- Pass temporary struct to function
- Initialize complex data inline
- Avoid named temporary variables
- Cleaner than temp variable + function call
Scope and lifetime:
- Compound literal has automatic storage duration
- Scope ends at end of enclosing block
- Don't return pointer to compound literal
Performance:
- Compiler may optimize to inline initialization
- No extra copy overhead
- Similar to temporary objects in C++
With designators:
- Mix positional and designated:
(Point){.x=1, 2} - Clear which fields are set
Limitations:
- Temporary lifetime (scope of enclosing block)
- Can't use static/extern storage
- Not available in C89/C90
c-compound-literals.md · Last modified: by 127.0.0.1
