On this page
_Generic
Prev: _Alignof | Up: builtins | Next: typeof
Rel: Preprocessor & Macros
Ref: cppreference — _Generic
Tags: #public #prog #c #builtins #tier/specialized
Availability
Built-in (Selection Expression (C11)) — requires no #include header.
Syntax & Overview
_Generic(expr, type1: val1, default: val_def)
Compile-time type-generic dispatch expression selecting a branch based on the controlling expression's type.
Notes & Pitfalls
- Compile-time type dispatch (C11): Zero runtime overhead—used to implement type-generic macros like
<tgmath.h>. - Default branch (
default:) catches unmatched types cleanly.
Example
#include <assert.h>
#include <string.h>
#define TYPE_NAME(x) _Generic((x), int: "int", double: "double", default: "other")
int main(void) {
assert(strcmp(TYPE_NAME(42), "int") == 0);
assert(strcmp(TYPE_NAME(3.14), "double") == 0);
}
Linked from
Related notes
- tuts/c/builtins/_Alignof Linked here; links to this page; shared tags: #builtins, #c, #prog, #tier
- tuts/c/builtins/typeof Linked here; links to this page; shared tags: #builtins, #c, #prog, #tier
- tuts/c/builtins Linked here; links to this page; shared tags: #builtins, #c, #prog
- tuts/c/compilation_and_internals/preprocessor_and_macros Linked here; shared tags: #c, #prog
- tuts/c/builtins/__FILE__ shared tags: #builtins, #c, #prog, #tier
- tuts/c/builtins/__func__ shared tags: #builtins, #c, #prog, #tier
- tuts/c/builtins/__LINE__ shared tags: #builtins, #c, #prog, #tier
- tuts/c/builtins/__STDC_VERSION__ shared tags: #builtins, #c, #prog, #tier
- tuts/c/builtins/_Atomic shared tags: #builtins, #c, #prog, #tier
- tuts/c/builtins/_Noreturn shared tags: #builtins, #c, #prog, #tier