18 Type-generic programming
This chapter covers
- Ubiquitous type-genericity
_Generic
expressions- Type inference with
auto
andtypedef
- Anonymous functions
Type-generic features are so deeply integrated into C that most programmers are probably not even aware of their omnipresence. We first identify and provide a more systematic view of a number of different features that do indeed provide type-genericity and that we already have seen throughout the book (see section 18.1). This discussion covers operators that work for multiple types, type promotions and conversions, macros, variadic functions, function pointers, and void
pointers. Then we introduce a more complicated programmable feature that came with C11: generic selection by means of the keyword _Generic
(section 18.2). That feature allows us to write code that, at compile time, distinguishes actions according to a fixed set of types, such as choosing different variants of a function if presented with a float
, double
, or long double
value.
One disadvantage of _Generic
is that, in general, it only works for a predefined fixed set of types and, therefore, quickly leads to a combinatorial explosion of cases. C23 introduced a new feature called type inference (keywords auto
, typeof
, and typeof_unqual
) that can be used to avoid writing such complicated code by consistently inferring type information from given expressions (section 18.3).