C Programming • C17 baseline, standards-specific features labeled
Designated Initializers and Compound Literals
Initialize aggregate fields by name and create temporary compound values with explicit lifetimes.
Designated initializers name structure members or array indices, which can make configuration data easier to review. Compound literals create typed objects; their lifetime depends on where they appear. These features are standardized in C99 and remain available in later C standards.
Example
struct point {
int x;
int y;
};
static int distance_squared(struct point value) {
return value.x * value.x + value.y * value.y;
}
int main(void) {
struct point origin = {.x = 0, .y = 0};
struct point offset = {.y = 4, .x = 3};
int result = distance_squared((struct point){.x = 3, .y = 4});
return origin.x + offset.x == 3 && result == 25 ? 0 : 1;
}
What to expect
The compound literal is passed by value as a struct point; designated fields make each initializer explicit.
Key idea: Do not return a pointer to a block-scope compound literal after its lifetime ends.