typestar

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

  1. (struct Point){1, 2} is a value, not a declaration.
  2. It can be passed straight into a call.
  3. Its lifetime is the enclosing block, so never return its address.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 4 in Values & storage, step 30 of 35 in Language basics.

← Previous Next →