Reading history

_Generic in C11: Type-Generic Macros

6 min read 2 views

Use C11's _Generic keyword to pick code based on an argument's type, such as one print macro for int, double and strings. Syntax, examples and limits.

C has no function overloading: you cannot write two functions called print, one for int and one for double. Since C11, the _Generic keyword offers the next best thing. It looks at the type of an expression at compile time and picks a matching result, which lets one macro name do the right thing for each type.

In this lesson you will learn

  • What problem _Generic solves
  • The syntax of a generic selection, step by step
  • How to build type-generic macros that call the right function
  • Surprises with character constants, arrays and qualifiers
  • When _Generic is the wrong tool

What _Generic Solves

The C maths library has sqrt for double, sqrtf for float and sqrtl for long double. Remembering which one to call is a chore, and calling the wrong one silently converts your value. The same problem appears with abs, labs and fabs, and with printing: each type needs a different printf format.

_Generic lets you hide those choices behind one name. The standard header <tgmath.h> uses exactly this technique, so that sqrt(x) picks the right version for x‘s type.

How a _Generic Selection Works

_Generic( controlling-expression,
          type1: result1,
          type2: result2,
          default: result_if_nothing_matches )
  1. The compiler works out the type of the controlling expression. The expression itself is never run.
  2. It compares that type with each listed type.
  3. The whole _Generic(...) is replaced by the matching result. If nothing matches and there is no default, compilation fails.

All of this happens at compile time, so it costs nothing while the program runs. Here is a macro that reports the type name of any expression:

#include <stdio.h>

#define TYPE_NAME(x) _Generic((x),      \
    int: "int",                         \
    long: "long",                       \
    double: "double",                   \
    float: "float",                     \
    char *: "char *",                   \
    default: "something else")

int main(void) {
    int count = 3;
    double price = 9.5;
    char word[] = "hello";
    printf("count is %s\n", TYPE_NAME(count));
    printf("price is %s\n", TYPE_NAME(price));
    printf("3.5f is %s\n", TYPE_NAME(3.5f));
    printf("word is %s\n", TYPE_NAME(word));        /* the array decays to char * */
    printf("'A' is %s\n", TYPE_NAME('A'));          /* character constants are int in C */
    printf("10L is %s\n", TYPE_NAME(10L));
    return 0;
}

Output

count is int
price is double
3.5f is float
word is char *
'A' is int
10L is long

Two lines are worth a second look. The array word is reported as char *, because the controlling expression goes through the usual conversions and an array becomes a pointer to its first element. And 'A' is an int in C, unlike C++, where it is a char. See character literals in C vs C++.

Type-Generic Macros in Practice

One print() for Several Types

The results of a generic selection do not have to be strings. They can be function names. Put the argument after the closing bracket, and the chosen function is called with it.

#include <stdio.h>

static void print_int(int x)           { printf("%d\n", x); }
static void print_double(double x)     { printf("%.2f\n", x); }
static void print_str(const char *s)   { printf("\"%s\"\n", s); }

/* One name, three functions: _Generic picks the function, then we call it. */
#define print(x) _Generic((x),          \
    int: print_int,                     \
    double: print_double,               \
    char *: print_str,                  \
    const char *: print_str)(x)

int main(void) {
    print(42);
    print(3.14159);
    print("sensor ready");
    return 0;
}

Output

42
3.14
"sensor ready"

The pattern is _Generic((x), type: function, ...)(x): the selection picks a function, and (x) calls it. Each function still has a normal, fixed type, so the compiler checks every call.

How <tgmath.h> Works Inside

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

/* How <tgmath.h> works inside: one name, a version per type. */
#define my_sqrt(x) _Generic((x), float: sqrtf, long double: sqrtl, default: sqrt)(x)

int main(void) {
    float f = 2.0f;
    double d = 2.0;
    printf("float  result: %.10f (sizeof %zu)\n", (double)my_sqrt(f), sizeof my_sqrt(f));
    printf("double result: %.10f (sizeof %zu)\n", my_sqrt(d), sizeof my_sqrt(d));
    printf("int argument uses default: %.4f\n", my_sqrt(9));
    return 0;
}

Output

float  result: 1.4142135382 (sizeof 4)
double result: 1.4142135624 (sizeof 8)
int argument uses default: 3.0000

A float argument calls sqrtf and returns a 4-byte float; a double calls sqrt. The int argument has no entry of its own, so default sends it to sqrt, where it is converted to double. Notice the small difference in the last digits: float keeps only about 7 significant digits.

Default Cases and Type Surprises

  1. Character constants are int. 'A' matches int, not char. A char variable does match char.
  2. Arrays become pointers. An array of char matches char *; you cannot match char[10].
  3. const on the outer level is dropped. A const int variable matches int. But a pointer to const char is a different type from a pointer to char, so list both, as the print macro above does.
  4. Each type may appear only once. Listing int twice is a compile error. On some systems long and long long, or int64_t and long, are the same type, which can cause duplicate entries in portable code.
  5. Without default, unknown types fail to compile. That is often what you want: a clear error is better than a wrong guess.
  6. It is C only. C++ does not support _Generic; it uses overloading and templates instead.

When Not to Use _Generic

_Generic shines for small, type-dispatching macros such as printing, maths and min/max helpers. It is a poor fit for large amounts of logic, and it cannot make a container like a “generic list”. For those, C programmers usually pass void * pointers plus a size or a callback, as qsort does. See function pointers in C.

Practice Exercises

Exercise 1. What does TYPE_NAME(5 / 2.0) print with the macro above?

Show answer

double. Dividing an int by a double gives a double.

Exercise 2. Write a macro ABS(x) that calls abs for int, labs for long and fabs for double.

Show answer
#define ABS(x) _Generic((x), int: abs, long: labs, double: fabs)(x)

Include <stdlib.h> and <math.h>.

Exercise 3. char c = 'x'; What do TYPE_NAME(c) and TYPE_NAME(c + 1) give if the macro has a char entry?

Show answer

c is char, but c + 1 is int, because arithmetic promotes char to int.

Frequently Asked Questions

Does _Generic slow my program down?

No. The choice is made by the compiler, and the controlling expression is never evaluated.

Which compilers support _Generic?

Any C11 compiler, including GCC 4.9 and later, Clang, and Microsoft Visual C++ from version 16.8 when compiling as C11 or C17.

Is _Generic the same as C++ templates?

No. Templates generate new code for each type. _Generic only chooses between expressions you have already written.

_Generic Summary

  • _Generic (C11) picks a result based on an expression’s type, at compile time.
  • Combine it with function names to build type-generic macros like print(x).
  • <tgmath.h> uses it to choose between sqrt, sqrtf and sqrtl.
  • Watch for 'A' being int, arrays becoming pointers and duplicate type entries.
Lessons are also marked complete when you click Next.