Type-generic expression

From cppreference.com
< c‎ | language

Implements a form of type-polymorphism mechanism.

Contents

[edit] Syntax

_Generic ( assignment-expression ,
type-name1 : assignment-expression1 ,
type-name2 : assignment-expression2 ,
... ... ...
type-namen : assignment-expressionn ,
default: assignment-expression (optional)

)

[edit] Explanation

The first assignment-expression is the controlling expression and determines the result of the generic selection. If the type of the controlling expression is compatible with one of the type-namei, then the result of the generic selection is the value of the assignment-expressioni in the generic association. Otherwise, the result expression of the generic selection is the expression in the default generic association. If a generic selection has no default generic association, then the type of the controlling expression must be compatible with exactly one of the types named in its generic association list.

[edit] Keywords

_Generic, default

[edit] Example

#include <stdio.h>
 
int main(void)
{
    printf("%d\n",_Generic( 1.0L, float:1, double:2, long double:3, default:0));
    printf("%d\n",_Generic( 1L, float:1, double:2, long double:3, default:0));
    printf("%d\n",_Generic( 1.0L, float:1, double:2, long double:3));
}

Possible output:

3
0
3