C Reference ยท Keywords and Statements
The _Generic selection
Reference for C11 _Generic: choose an expression by the type of a controlling expression, build type-generic macros and avoid its common pitfalls.
_Generic picks one of several expressions at compile time, based on the type of a controlling expression. It is the closest thing C has to overloading: a macro that wraps _Generic can call print_int, print_double or print_string depending on its argument.
Only the selected branch is used; the other branches are not evaluated, but they must still be valid expressions syntactically. The controlling expression is not evaluated either. _Generic was added in C11 and is still spelled with the underscore in C23.
#define type_name(x) _Generic((x), int: "int", double: "double", default: "other")
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
_Generic(controlling-expression, type-name1: expression1, type-name2: expression2, default: default-expression)
| Part | Description |
|---|---|
| controlling expression | Its type decides the branch. Not evaluated. Lvalue conversion applies first. |
type-name: expression |
An association. No two associations may name compatible types. |
default: |
Optional fallback used when no type matches. At most one. |
Returns: the value of the selected expression.
Errors: if no association matches and there is no default, the program does not compile. Two branches with compatible types (for example int and a typedef of int) are an error.
Usage notes
- Lvalue conversion. The controlling expression is converted first: top-level
const/volatileare dropped, arrays decay to pointers, and functions to function pointers. That is whyconst intneeds no separate branch, butconst char *does (the pointee keeps itsconst). - Character constants have type
intin C, so'a'selects theintbranch. - Unselected branches must still compile. Choosing functions by name and calling the result, as in
print, avoids calls with the wrong argument type. - Standard use:
<tgmath.h>is implemented with it, sosqrt(x)callssqrtf,sqrtorsqrtlby type. - Not a runtime check. It sees the static type, not what a
void *actually points to. - Use sparingly in macros: the error messages can be long, and each macro argument should be evaluated once.
- C23
nullptr. Its typenullptr_tcan be a branch of its own.
Related
typeof,<tgmath.h>,#define, function-like macros- Lessons: Macros, Modern C