Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
_Generic keyword in C ? 1: 20
_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
#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
", typecheck(2353463456356465));
printf( "passing a float value to the macro, result is %d
", typecheck(4.32f));
printf( "passing a int value to the macro, result is %d
", typecheck(324));
printf( "passing a string value to the macro, result is %d
", 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
Advertisements
