C语言中的通用关键字用法介绍

2021年3月9日15:44:37 发表评论 753 次浏览

的主要缺点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

因此, 我们避免使用Macro。但是在用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

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: