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
-
Economics & Finance
Generic keyword in C ?
The _Generic keyword in C (introduced in C11) enables type-generic programming by allowing different expressions to be selected based on the type of an argument. This provides a solution to the type-safety limitations of traditional macros.
Syntax
_Generic(expression, type1: expression1, type2: expression2, ..., default: default_expression)
Problem with Traditional Macros
Traditional C macros lack type checking and perform the same operation regardless of data type −
#include <stdio.h>
#define INCREMENT(X) ++X
int main() {
int x = 5;
float y = 2.56;
char z = 'A';
printf("Integer Increment: %d<br>", INCREMENT(x));
printf("Float Increment: %f<br>", INCREMENT(y));
printf("Character Increment: %c<br>", INCREMENT(z));
return 0;
}
Integer Increment: 6 Float Increment: 3.560000 Character Increment: B
Solution Using _Generic Keyword
The _Generic keyword allows us to define type-specific behavior for different data types −
#include <stdio.h>
#define INCREMENT(X) _Generic((X), char: X+10, int: X+1, float: X+2.5, default: 0)
int main() {
int x = 5;
float y = 2.56;
char z = 'A';
printf("Integer Increment: %d<br>", INCREMENT(x));
printf("Float Increment: %f<br>", INCREMENT(y));
printf("Character Increment: %c<br>", INCREMENT(z));
return 0;
}
Integer Increment: 6 Float Increment: 5.060000 Character Increment: K
How It Works
The _Generic expression evaluates the type of the first argument and selects the corresponding expression:
- For
inttype: adds 1 - For
floattype: adds 2.5 - For
chartype: adds 10 (ASCII value increment) - For unknown types: returns default value 0
Key Points
-
_Genericis available in C11 and later versions - Type selection happens at compile time, not runtime
- The
defaultcase is optional but recommended - Only one expression is evaluated based on the type match
Conclusion
The _Generic keyword provides type-safe macro programming in C, allowing different behaviors for different data types while maintaining the efficiency of macros. It bridges the gap between C's type system and generic programming.
