_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.

CategoryC11 features
KindKeyword / Statement
C standardC11

📝 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏