_Generic keyword in C

A major drawback of Macro in C/C++ is that the arguments are strongly typed checked i.e. a macro can operate on different types of variables(like char, int ,double,..) without type checking.

 

// 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;

}

Output:

eeks 11

Therefore we avoid to use Macro. But after the implementation of C11 standard in C programming, we can use Macro with the help of a new keyword i.e. “_Generic”. We can define MACRO for the different types of data types. For example, the following macro INC(x) translates to INCl(x), INC(x) or INCf(x) depending on the type of x:

 

 

#define INC(x) _Generic((x), long double: INCl, \
                              default: INC, \
                              float: INCf)(x)

Example:-

 

 

// 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;

}

 

Output:
Note: If you are running C11 compiler then the below mentioned output will be come.

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;

}

 

 

Output:

2
0

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值