Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

_Generic — selection by type

_Generic selects an expression by compatible type rather than value; its controlling expression is not evaluated.

Version: C23; repository compiler flag, production runtime not attested

Syntax

_Generic(expression, type_name: result_expression, default: fallback_expression)

_Generic selects an expression during translation. The result preserves the selected expression's type, value, and category, including lvalue status.

The controlling type accounts for lvalue conversion and array/function-to-pointer conversions. Associations require complete object types that are not variably modified; compatible types cannot be repeated.

Optional default occurs at most once; without it, a match is required. The controlling expression and unselected expressions are not evaluated. Unselected expressions must still be semantically valid.

In the example, TYPE_NAME(n++) does not increment n; "text" selects default.

Examples

#include <stdio.h>

#define TYPE_NAME(x) _Generic((x), int: "int", double: "double", default: "other")

int main(void)
{
    int n = 7;
    puts(TYPE_NAME(n++));
    puts(TYPE_NAME(2.0));
    puts(TYPE_NAME("text"));
    printf("%d\n", n);
    return 0;
}

Result

int
double
other
7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources