_Generic关键字在C吗?1:20

C中的_Generic关键字用于为不同的数据类型定义MACRO。在C11标准版本中,此新关键字已添加到C编程语言中。_Generic关键字用于帮助程序员以更有效的方式使用MACRO。

此关键字根据变量的类型转换MACRO。让我们举个例子

#define dec(x) _Generic((x), long double : decl, \ default : Inc , \ float: incf )(x)

上面的语法是如何将任何MACRO声明为不同方法的泛型。

让我们以示例代码为例,该代码将定义一个MACRO,该MACRO将基于数据类型返回值-

示例

#include <stdio.h>
#define typecheck(T) _Generic( (T), char: 1, int: 2, long: 3, float: 4, default: 0)
int main(void) {
   printf( "passing a long value to the macro, result is %d \n", typecheck(2353463456356465));
   printf( "passing a float value to the macro, result is %d \n", typecheck(4.32f));
   printf( "passing a int value to the macro, result is %d \n", typecheck(324));
   printf( "passing a string value to the macro, result is %d \n", typecheck("Hello"));
   return 0;
}

输出结果

passing a long value to the macro, result is 3
passing a float value to the macro, result is 4
passing a int value to the macro, result is 2
passing a string value to the macro, result is 0