_Generic keyword in C ? 1: 20

CServer Side ProgrammingProgramming

_Generic keyword in C is used to define MACRO for different data types. This new keyword was added to the C programming language in C11 standard release. the _Generic keyword is used to help the programmer use the MACRO in a more efficient way.

this keyword translate the MACRO based on the type of the variable. let's take an example ,

#define dec(x) _Generic((x), long double : decl, \ default : Inc , \ float: incf )(x)

The above syntax is how to declare any MACRO as generic for different methods.

Let's take an example code, this code will define a MACRO that will return values based on the data type −

Example

 Live Demo

#include <stdio.h>
#define typecheck(T) _Generic( (T), char: 1, int: 2, long: 3, float: 4, default: 0)
int main(void) {
   printf( "passing a long value to the macro, result is %d \n", typecheck(2353463456356465));
   printf( "passing a float value to the macro, result is %d \n", typecheck(4.32f));
   printf( "passing a int value to the macro, result is %d \n", typecheck(324));
   printf( "passing a string value to the macro, result is %d \n", typecheck("Hello"));
   return 0;
}

Output

passing a long value to the macro, result is 3
passing a float value to the macro, result is 4
passing a int value to the macro, result is 2
passing a string value to the macro, result is 0
raja
Published on 04-Oct-2019 06:57:10
Advertisements