Skip to content
Related Articles

Related Articles

Improve Article

_Generic keyword in C

  • Difficulty Level : Medium
  • Last Updated : 03 Jan, 2019

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

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.

Take a step-up from those “Hello World” programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.



My Personal Notes arrow_drop_up
Recommended Articles
Page :