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 int type: adds 1
  • For float type: adds 2.5
  • For char type: adds 10 (ASCII value increment)
  • For unknown types: returns default value 0

Key Points

  • _Generic is available in C11 and later versions
  • Type selection happens at compile time, not runtime
  • The default case 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.

Updated on: 2026-03-15T10:56:07+05:30

412 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements