_Generic keyword in C

4

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:

eeks10

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

This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

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

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



4 Average Difficulty : 4/5.0
Based on 2 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.