liveBook · Manning

_Generic

As explained in Modern C, Third Edition

A generic selection is a C11 expression construct that selects one expression from a set based on the type of a controlling expression.

A macro can offer one `fabs(X)` interface while choosing `fabsf`, `fabsl`, or `fabs` according to the type of `X`. This is **generic selection**: a C11 expression that makes a compile-time choice among expressions associated with types. section 18.2

#define fabs(X)       \
_Generic((X),         \
  float: fabsf,       \
  long double: fabsl, \
  default: fabs)(X)

Here, a `float` argument selects `fabsf`, a `long double` selects `fabsl`, and `default` selects `fabs` for other types, including `double` and integer types. The `_Generic` expression selects a function; the trailing `(X)` calls it. section 18.2

_Generic(\textit{controlling expression},
  \textit{type1}: \textit{expression1},
  ... ,
  \textit{typeN}: \textit{expressionN})

The controlling expression supplies the type used for selection. Each association pairs a type with a result expression; one association may use `default` instead of a type. `_Generic` is an expression, not a macro feature, though it fits naturally inside a macro. section 18.2

**TAKEAWAY:** Choose `_Generic` when an interface needs to distinguish a fixed set of types. For a two-argument `min` interface, the controlling expression can be the sum of the arguments, so their promotions and conversions affect the type used for selection. Covering more combinations can quickly multiply the cases; C23 type inference offers another approach to type-dependent code. section 18.2 section 18.0

How Modern C, Third Edition covers it

How deep it goes
Defines the expression form and works through function dispatch, then introduces two-argument selection and its conversion concerns.
Examples
Uses a `fabs` dispatch macro and a two-argument `min` interface; proposes extensions to complex and integer types.
What it assumes
Assumes familiarity with macros, functions, and arithmetic types while introducing generic-selection syntax.
What you can do after
Apply it via `_Generic` to dispatch a macro to functions selected by argument type.
How it connects
Links macro expansion, function pointers, arithmetic conversions, and type inference to type-generic programming.

Also explained in

Compare how 2 books explain _Generic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.