Skip to content
Quantoros

Why is Generic useful, and how is it different from C++ overloading?

C++Level: IntermediateC Language Essentials

Why is _Generic useful, and how is it different from C++ overloading?

Hints
  • Identify types, object lifetimes and compile-time decisions.
  • Separate language guarantees from a particular compiler's behavior.

Answer

_Generic Type Selection (C11)

:Source: src/c/generic

_Generic enables type-generic macros by selecting expressions based on the type of the controlling expression. This provides a form of function overloading in C, commonly used for type-safe math functions and print formatters. The selection happens at compile time with no runtime overhead.

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

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

#define type_name(x) _Generic((x), \
    int: "int", \
    float: "float", \
    double: "double", \
    char *: "char *", \
    default: "unknown" \
)

int main(void) {
  printf("abs(-5) = %d\n", abs_val(-5));
  printf("abs(-3.14) = %f\n", abs_val(-3.14));

  int i; float f; char *s;
  printf("i is %s, f is %s, s is %s\n",
         type_name(i), type_name(f), type_name(s));
}
$ gcc -std=c11 -o generic main.c -lm && ./generic
abs(-5) = 5
abs(-3.14) = 3.140000
i is int, f is float, s is char *

Answer section

Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT

Related questions