CKTIS / C
generic selection — concept C23
A `_Generic` expression selects an association from the type of its controlling expression without evaluating that expression; the result has the selected expression’s value and type. The list cannot contain two compatible types, at most one association may match, and no match requires `default`; check qualifier and conversion rules for the selected C revision.
Version: C23
Syntax
generic selectionA _Generic expression selects an association from the type of its controlling expression without evaluating that expression; the result has the selected expression’s value and type. The list cannot contain two compatible types, at most one association may match, and no match requires default; check qualifier and conversion rules for the selected C revision.
Use _Generic for a thin typed wrapper that selects the proper function, such as min_int or min_double, without evaluating the controlling expression. Every association expression must be syntactically and semantically valid even though only the selected one is evaluated; document all accepted types.
Test integer literals of different types, a qualified lvalue, an array, and a pointer because conversions of the controlling expression affect matching. Compatible types cannot appear twice, and default should either support other types or deliberately produce a clear compile-time error.
Examples
#include <stdio.h>
#define TYPE_NAME(x) _Generic((x), int: "int", double: "double", default: "other")
int main(void) { puts(TYPE_NAME(3.0)); return 0; }
Result
double
A `_Generic` expression selects an association from the type of its controlling expression without evaluating that expression; the result has the selected expression’s value and type. The list cannot contain two compatible types, at most one association may match, and no match requires `default`; check qualifier and conversion rules for the selected C revision.