Compound literals in C
An unnamed value of struct or array type, built where it is needed.
struct Point {
int x;
int y;
};
static int manhattan(struct Point a, struct Point b) {
int dx = a.x - b.x;
int dy = a.y - b.y;
return (dx < 0 ? -dx : dx) + (dy < 0 ? -dy : dy);
}
int distances(void) {
int near = manhattan((struct Point){0, 0}, (struct Point){3, 4});
int *scratch = (int[]){1, 2, 3, 4};
return near + scratch[3];
}
How it works
(struct Point){1, 2}is a value, not a declaration.- It can be passed straight into a call.
- Its lifetime is the enclosing block, so never return its address.
Keywords and builtins used here
Pointdistancesintmanhattanreturnstaticstructvoid
The run, in numbers
- Lines
- 16
- Characters to type
- 332
- Tokens
- 130
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 87 seconds.
Step 4 of 4 in Values & storage, step 30 of 35 in Language basics.