_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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章