18 Type-generic programming

 

This chapter covers

  • Ubiquitous type-genericity
  • _Generic expressions
  • Type inference with auto and typedef
  • 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).

18.1 Inherent type-generic features in C

18.1.1 Operators

18.1.2 Default promotions and conversions

18.1.3 Macros

18.1.4 Variadic functions

18.1.5 Function pointers

18.1.6 void pointers

18.1.7 Type-generic C library functions

18.2 Generic selection

18.3 Type inference

18.3.1 The auto feature

18.3.2 The typeof feature

18.4 Anonymous functions

Summary