Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 135 ยท Preprocessor

_Generic and Type-Generic Macros

Learn C11 _Generic generic selection - write macros that pick code by type, emulate overloading, avoid double evaluation with typeof, and use tgmath.h.

In C++ or Java you can write several functions called print, one for int, one for double, one for strings, and the compiler picks the right one. C has no function overloading: every function name is unique. For decades that meant the standard library needed separate names such as abs, labs, fabs and fabsf, and your own code needed print_int and print_double.

C11 added a small but powerful feature, generic selection, spelled _Generic. It lets an expression choose one of several alternatives based on the type of another expression, at compile time. Combined with a macro, it gives you a single name that dispatches by type, just like an overloaded function. You will learn the syntax, the type rules that cause surprises, how to build type-generic wrappers, how to avoid evaluating arguments twice, and how the standard <tgmath.h> header uses the same idea. You should be comfortable with macros and function pointers first.

The syntax

C
_Generic( controlling-expression,
          type1: result1,
          type2: result2,
          default: fallback )

The compiler works out the type of the controlling expression, finds the association whose type matches, and the whole _Generic(...) becomes that association's result expression. The default: association is optional, and it is used when no type matches. If nothing matches and there is no default, the program does not compile.

Three facts define how it behaves:

  1. It is resolved at compile time. There is no runtime check and no cost. The choice is made once, while compiling, and the other alternatives disappear.
  2. The controlling expression is never evaluated. Only its type is used. _Generic(i++, int: 1, default: 0) does not increment i.
  3. It is not a macro. It is part of the language, and it understands types. The preprocessor does not, which is why _Generic is usually wrapped in a macro: the macro gives you a friendly name, and _Generic supplies the type awareness.
flowchart LR
    A["TYPE_NAME(x)<br/>macro"] --> B["_Generic(x, ...)"]
    B --> C{"compile time:<br/>type of x?"}
    C -->|"int"| D["picks the int alternative"]
    C -->|"double"| E["picks the double alternative"]
    C -->|"anything else"| F["picks default"]
    D --> G["compiled code contains<br/>only the chosen expression"]
    E --> G
    F --> G

The type of the argument decides which alternative remains in the program. Nothing is tested while the program runs.

A first example: naming types

The simplest use is a macro that turns a value's type into a string:

C Asking for the type of a value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Some lines are surprising, and they teach the rules:

  • 'q' has type int in C (not char, as in C++). Character constants are integers.
  • 1.5f + 1 is a float (the integer converts to float), and count * pi is a double, following the normal type conversions.
  • "text" and buffer both match char *. The controlling expression goes through array-to-pointer decay, so an array of char becomes a char *. That is why numbers is not an "int array": it falls through to default, since int * is not in the list.
  • In C23, true has type bool. Before C23 it is the int constant 1.

Type rules you need to know

  • Qualifiers are dropped from the controlling expression. A const int variable matches the plain int association, because the expression undergoes lvalue conversion first. (Older C11 compilers disagreed about this; C23 settles it.) But pointer targets keep their qualifiers: const char * and char * are different types and need separate associations, as above.
  • Associations are exact. There is no "any integer" or "any pointer" wildcard. char, signed char and unsigned char are three distinct types; so are int and long, even when they have the same size.
  • No duplicate types. Two associations for the same type is an error, and so is a type that is compatible with another (for instance, listing int twice).
  • Every alternative must be valid code. The unselected alternatives are not executed, but they are still parsed and checked by the compiler. This catches many beginners, as the next section shows.

Building a type-generic function

The classic recipe is to select a function, not a call, and apply the arguments outside _Generic. This way every alternative is just a name of a function and is always valid:

C
#define print(x) _Generic((x),      \
    int: print_int,                  \
    double: print_double,            \
    const char *: print_string,      \
    char *: print_string)(x)

Compare the broken-looking alternative that puts the call inside: int: print_int(x). If x is a double, the compiler still has to compile print_int(x) (which would silently convert the value), and with a string it would be a hard error, because a char * cannot be passed to an int parameter. Selecting just the function name avoids this, and the final (x) is applied to the one function that was chosen.

C One name, several functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The last part shows another favorite idiom: choosing a printf format string by type. Because _Generic returns a string literal, printf(format_of(x), x) is as safe as writing the format by hand. Note that grade is a char, so it matches char and prints as a letter, while print('A') would be an int.

Be careful with the print macro: its name would collide with any real function called print, and macros do not respect scope. Prefix or capitalize macro names that are part of a public header.

Dispatching with a generic API

Generic selection is most useful when a library wants one friendly name for several implementations. Suppose we have a tiny "box" that stores a value of a few types and can report it. The user calls box_set(&box, value) and the macro finds the matching setter:

C A generic setter for a tagged value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

If you pass an unsupported type, such as box_set(&box, &box), the compiler stops with an error along the lines of "'_Generic' selector of type 'Box *' is not compatible with any association". This is what you want from an API: a bad call is rejected at compile time, not by a crash. If you prefer a friendlier message, add a default: alternative that names a function designed to fail, for example one declared with an attribute that triggers a diagnostic, or use static_assert (see _Static_assert and C23 Attributes).

Avoiding double evaluation

Generic macros often need to mention an argument twice, once for the type and once for the work, and that risks evaluating a side effect twice. The classic example is MAX:

C
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int m = MAX(i++, j);       /* i++ may run twice! */

_Generic does not help with this by itself, because the controlling expression is not evaluated. But C23's standard typeof operator does: it gives you a type to declare a temporary with, so each argument is evaluated exactly once. Statement expressions ({ ... }) are a GCC and Clang extension and not standard C, so the portable form wraps the logic in a function and uses _Generic plus typeof for the small pieces:

C typeof for single evaluation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

SQUARE_WRONG(next()) expands to next() * next(), calling the function twice (10 and 20 give 200, calls is 2). The function-based SQUARE calls next() once because the argument is passed to a real function exactly once. The lesson: when a generic macro would need an argument more than once, dispatch to a function (as above) or copy it into a typeof temporary.

The standard library's own type-generic macros

The C library uses the same feature in <tgmath.h>. Include it, and sqrt, sin, pow, fabs, exp and many more become type-generic macros: sqrt(2.0f) calls sqrtf, sqrt(2.0) calls sqrt, sqrt(2.0L) calls sqrtl, and with a complex argument they call csqrt and its siblings (see Complex Numbers). So fabs(x) works whatever the type of x is, with no manual choice between fabsf and fabs. In your own code, _Generic is the tool for creating the same kind of interface.

Limits and good practice

  • _Generic selects by type only. It cannot inspect values, array lengths or whether a type is an integer in general; you list the types you support.
  • It works on the compile-time type of the expression. A void * that points to an int is still a void *, so use it for static types, not for runtime polymorphism (for that you need tags, as in the Box example, or function pointers).
  • Keep the macro small: make it a thin dispatcher in front of real functions. The functions can be debugged, have proper types and do not repeat arguments.
  • Put parentheses around macro parameters and wrap multi-statement macros in do { } while (0), as explained in Macros.
  • Add a default: only when a fallback makes sense. Without it, unsupported types give a compile error, which is usually better.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When is the alternative in a _Generic expression chosen?

    _Generic is part of the language, not the preprocessor. The compiler picks the association from the static type and discards the rest.
  2. 2. What does TYPE_NAME('a') report in C, when the macro lists char and int separately?

    A character constant has type int in C (unlike C++), so the int association is chosen.
  3. 3. In a generic macro, why select function names and apply (x) afterwards, rather than writing int: print_int(x) inside each association?

    Every alternative must be valid code even when it is not chosen. Selecting only the function name and applying the argument outside avoids invalid calls in the unselected branches.
  4. 4. Given const int limit = 5;, which association does _Generic((limit), int: 1, double: 2, default: 3) pick?

    The controlling expression loses its top-level qualifier, so a const int variable matches int. Qualifiers on pointer targets (const char * versus char *) are kept, so those need separate associations.
  5. 5. What happens if no association matches and there is no default:?

    Compile-time failure is a feature. It rejects unsupported types before the program ever runs.

Summary

  • _Generic(expr, type: result, ..., default: result) chooses one result expression by the type of expr, at compile time, with no runtime cost.
  • The controlling expression is not evaluated; arrays decay to pointers and top-level qualifiers are dropped, but pointer targets keep const.
  • Wrap it in a macro to emulate overloading, and select function names rather than calls so that every alternative is valid.
  • Character constants are int, so TYPE_NAME('a') is int; true is bool in C23.
  • Avoid evaluating macro arguments twice: dispatch to functions or use typeof temporaries.
  • A missing match without default: is a compile error, which is useful for rejecting unsupported types; <tgmath.h> is the standard library's example of the technique.

Next: File Handling