Generic keyword in C ?

CServer Side ProgrammingProgramming

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\n", INCREMENT(x));
   printf("Float Increment: %f\n", INCREMENT(y));
   printf("Character Increment: %c\n", 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\n", INCREMENT(x));
   printf("Float Increment: %f\n", INCREMENT(y));
   printf("Character Increment: %c\n", INCREMENT(z));
}

Output

Integer Increment: 6
Float Increment: 5.060000
Character Increment: K
raja
Published on 26-Jul-2019 09:13:11
Advertisements