On this page
  1. _Generic
  2. Availability
  3. Syntax & Overview
  4. Notes & Pitfalls
  5. Example

_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

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