typestar

_Generic in C

C11's type-based selection: one macro name, a different call per argument type.

#include <stdio.h>

#define TYPE_NAME(x) _Generic((x), \
    int: "int", \
    long: "long", \
    double: "double", \
    char *: "char *", \
    default: "something else")

#define ABS(x) _Generic((x), int: abs_int, double: abs_double)(x)

static int abs_int(int v) {
    return v < 0 ? -v : v;
}

static double abs_double(double v) {
    return v < 0.0 ? -v : v;
}

void dispatch(void) {
    printf("%s %s %s\n", TYPE_NAME(1), TYPE_NAME(1.0), TYPE_NAME("text"));
    printf("%d %.1f\n", ABS(-3), ABS(-2.5));
}

How it works

  1. The controlling expression's type picks the branch.
  2. Nothing is evaluated except the branch selected.
  3. It is how tgmath.h dispatches on float versus double.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
476
Tokens
100
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 55 seconds.

Type this snippet

Step 1 of 2 in Escape hatches, step 11 of 13 in Unions, bitfields & undefined behavior.

← Previous Next →