Generic keyword in C ?


As we know that the Macros are used in C or C++, but there is no facility for type checking. The macros can take any type of argument in it. The following example will show this case clearly.

Example

 Live Demo

#include<stdio.h>
#define INCREMENT(X) ++X
main() {
   int x = 5; float y = 2.56; char z = 'A';
   printf("Integer Increment: %d
", INCREMENT(x));    printf("Float Increment: %f
", INCREMENT(y));    printf("Character Increment: %c
", INCREMENT(z)); }

Output

Integer Increment: 6
Float Increment: 3.560000
Character Increment: B

That is the problem of macro. In the later version of C, we can use macro by using ‘_Generic’ keyword. Using this we can define macro using different types of datatypes. Let us see one example.

Example

 Live Demo

#include<stdio.h>
#define INCREMENT(X) _Generic( (X), char: X+10, int: X+1, float: X+2.5, default: 0)
main() {
   int x = 5; float y = 2.56; char z = 'A';
   printf("Integer Increment: %d
", INCREMENT(x));    printf("Float Increment: %f
", INCREMENT(y));    printf("Character Increment: %c
", INCREMENT(z)); }

Output

Integer Increment: 6
Float Increment: 5.060000
Character Increment: K

Updated on: 30-Jul-2019

187 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements