一个主要的缺点 C/C中的宏++ 参数是强类型检查的,即宏可以对不同类型的变量(如char、int、double等)进行操作没有类型检查。
null
// 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”。我们可以为不同类型的数据类型定义宏。例如,以下宏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" , _Generic( 1.0L, float :1, double :2, long double :3, default :0)); printf ( "%d" , _Generic( 1L, float :1, double :2, long double :3, default :0)); printf ( "%d" , _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" , geeks( 'A' )); // Here A is a string. printf ( "%d" ,geeks( "A" )); return 0; } |
输出:
2 0
本文由 比沙尔·库马尔·杜比 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END