c / expert
Snippet
Transient Data Transfer via Dynamic C99 Compound Literals
C99 compound literals create unnamed objects on the stack with block scope. Taking their address allows passing complex struct instances to functions inline without allocating dynamic heap memory or declaring explicit local variables.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>typedef struct {int id;const char *tag;} ConfigHeader;void print_config(const ConfigHeader *cfg) {printf("ID: %d, Tag: %s\n", cfg->id, cfg->tag);}int main(void) {print_config(&(ConfigHeader){ .id = 404, .tag = "NOT_FOUND" });print_config(&(ConfigHeader){ .id = 200, .tag = "OK" });return 0;}
Breakdown
1
(ConfigHeader){ .id = 404, .tag = "NOT_FOUND" }
Constructs an anonymous ConfigHeader object initialised with designated member values on the local stack frame.
2
&(ConfigHeader){ ... }
Obtains a temporary pointer to the compound literal to satisfy the function signature.