Tutorialspoint.dev

_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 ", _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;
}

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 ", geeks('A')); 
   
    // Here A is a string.
    printf("%d",geeks("A"));
      
    return 0;
}

Output:

2
0

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



This article is attributed to GeeksforGeeks.org

tags:

C C

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter