_Generic C11 type-generic selection
_Generic C11 type-generic selection
C11's _Generic selects by converted type at compile time. Control is unevaluated; selection determines value and type. Use default or cover expected types.
| Category | C11 features |
|---|---|
| Kind | Keyword / Statement |
| C standard | C11 |
📝 Syntax
#define type_name(x) _Generic((x), int: "int", double: "double")
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
int double other
ℹ️ Info The short variable selects default, so GCC 10.2 prints int double other. Selection depends only on type: the control expression small is not evaluated at runtime, and unselected result expressions are not executed.
🏷️ Related C11 features
📚 Related Tutorials
❓ FAQ
QDoes _Generic's controlling expression perform side effects?
ANo. The controlling expression determines a type but is not evaluated, so TYPE_NAME(i++) does not execute i++. Only the selected result expression is evaluated under the normal rules.
QWhat happens if _Generic has neither a matching type nor default?
AThis violates the generic-selection constraints and is diagnosed during translation; no branch is chosen randomly at runtime. Providing default for an open-ended set of types avoids this compilation failure.
QDoes _Generic('a', char: ..., int: ...) match char?
ANo. In C, an ordinary character constant such as 'a' has type int, so it matches the int association. Use an appropriate char object expression when a char type is required.