_Generic keyword in C ? 1: 20

The _Generic keyword in C is used to define type-generic macros that can work with different data types. This keyword was introduced in the C11 standard to enable compile-time type selection, allowing a single macro to behave differently based on the type of its argument.

Syntax

#define macro_name(x) _Generic((x), \
    type1: expression1, \
    type2: expression2, \
    default: default_expression \
)(x)

The _Generic expression evaluates to one of the specified expressions based on the type of the controlling expression (x).

Parameters

  • Controlling expression − The expression whose type determines the selection
  • Type associations − Pairs of types and corresponding expressions
  • default − Optional fallback expression for unmatched types

Example 1: Type Detection Macro

This example demonstrates a macro that returns different values based on the input data type −

#include <stdio.h>

#define typecheck(T) _Generic((T), \
    char: 1, \
    int: 2, \
    long: 3, \
    float: 4, \
    double: 5, \
    default: 0)

int main() {
    printf("char type: %d
", typecheck('A')); printf("int type: %d
", typecheck(324)); printf("long type: %d
", typecheck(2353463456L)); printf("float type: %d
", typecheck(4.32f)); printf("double type: %d
", typecheck(4.32)); printf("string type: %d
", typecheck("Hello")); return 0; }
char type: 1
int type: 2
long type: 3
float type: 4
double type: 5
string type: 0

Example 2: Type-Generic Absolute Value Function

This example shows how to create a generic absolute value macro that works with different numeric types −

#include <stdio.h>
#include <math.h>

#define ABS(x) _Generic((x), \
    int: abs(x), \
    long: labs(x), \
    float: fabsf(x), \
    double: fabs(x), \
    long double: fabsl(x))

int main() {
    int i = -42;
    long l = -123456L;
    float f = -3.14f;
    double d = -2.718;
    
    printf("ABS(%d) = %d
", i, ABS(i)); printf("ABS(%ld) = %ld
", l, ABS(l)); printf("ABS(%.2f) = %.2f
", f, ABS(f)); printf("ABS(%.3f) = %.3f
", d, ABS(d)); return 0; }
ABS(-42) = 42
ABS(-123456) = 123456
ABS(-3.14) = 3.14
ABS(-2.718) = 2.718

Key Points

  • The _Generic keyword provides compile-time type selection, not runtime
  • Type associations are evaluated at compile time based on the argument's type
  • The default case is optional but recommended for unhandled types
  • Works with both built-in and user-defined types
  • Requires C11 or later compiler support

Conclusion

The _Generic keyword enables powerful type-generic programming in C by allowing macros to select different expressions based on argument types. This feature improves code reusability and type safety in modern C programming.

Updated on: 2026-03-15T12:10:32+05:30

910 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements