这篇文章上次修改于 731 天前,可能其部分内容已经发生变化,如有疑问可询问作者。

参考
【Just For Fun】C - 宏开发 - _Generic() 泛型

_Generic() 语法:

_Generic ( controlling-expression , association-list )

其中 association-list 為:type-name : expression / default : expression 。
—— 简单来说,即是:
_Generic(<var>, <type1> : <exp1>, <type2> : <exp2>, ...) 。

_Generic () 特性

_Generic() 是编译期的。

default 非必要。

如果类型列表中找不到对应的类型,并且没有 default,会出现编译错误。此关键字为c11新添加的关键字,会匹配第一个参数的类型,并返回自定义返回值.

例一:

#define GENERAL_ABS(x) _Generic((x),int:abs,float:fabsf,double:fabs)(x)

例二:

#define getTypeName(x) _Generic((x), _Bool:"_Bool",\
    char: "char", \
    signed char: "signed char", \
    unsigned char: "unsigned char", \
    short int: "short int", \
    unsigned short int: "unsigned short int", \
    int: "int", \
    unsigned int: "unsigned int", \
    long int: "long int", \
    unsigned long int: "unsigned long int", \
    long long int: "long long int", \
    unsigned long long int: "unsigned long long int", \
    float: "float", \
    double: "double", \
    long double: "long double", \
    char *: "pointer to char", \
    void *: "pointer to void", \
    int *: "pointer to int",\
    default: "other")