C/C++中宏的一个主要缺点是参数经过了强类型检查,即宏可以在不进行类型检查的情况下对不同类型的变量(如 char、int、double、..)进行操作。
// C program to illustrate macro function.
#include<stdio.h>
#define INC(P) ++P
int main()
{
char *p = "Geeks";
int x = 10;
printf("%s ", INC(p));
printf("%d", INC(x));
return 0;
}
输出:
eeks 11
因此我们避免使用宏。但是在C编程中实现了C11标准之后,我们可以借助一个新的关键字“_Generic”来使用Macro。我们可以为不同类型的数据类型定义 MACRO。例如,以下宏 INC(x) 根据 x 的类型转换为 INCl(x)、INC(x) 或 INCf(x):
#define INC(x) _Generic((x), long double: INCl, \
default: INC, \
float: INCf)(x)
例子:-
// C program to illustrate macro function.
#include <stdio.h>
int main(void)
{
// _Generic keyword acts as a switch that chooses
// operation based on data type of argument.
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));
return 0;
}
输出:
注意:如果您正在运行 C11 编译器,则会出现下面提到的输出。
3 0 3
// C program to illustrate macro function.
#include <stdio.h>
#define geeks(T) _Generic( (T), char: 1, int: 2, long: 3, default: 0)
int main(void)
{
// char returns ASCII value which is int type.
printf("%d\n", geeks('A'));
// Here A is a string.
printf("%d",geeks("A"));
return 0;
}
输出:
2 0