Skip to content
Tutorials Center
My learning

Topics

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.

C
#define type_name(x) _Generic((x), int: "int", double: "double", default: "other")

Try it

C Naming a type

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.

C A type-generic print macro

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

C
_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/volatile are dropped, arrays decay to pointers, and functions to function pointers. That is why const int needs no separate branch, but const char * does (the pointee keeps its const).
  • Character constants have type int in C, so 'a' selects the int branch.
  • 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, so sqrt(x) calls sqrtf, sqrt or sqrtl by 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 type nullptr_t can be a branch of its own.