Type generic macros
In C11, a new keyword has been introduced: _Generic
. It can be used to write macros that are type-aware at compile time. In other words, you can write macros that can change their value based on the type of their arguments. This is usually called generic selection. Look at the following code example in Code Box 12-6:
#include <stdio.h> #define abs(x) _Generic((x), \ int: absi, \ double: absd)(x) int absi(int a) { return a > 0 ? a : -a; } double absd(double a) { return a > 0 ? a : -a; } int main(int argc, char** argv) { printf("abs(-2): %d\n", abs(-2)); printf("abs(2.5): %f\n", abs(2.5));; return 0; }
Code Box 12-6: Example of a generic macro
As you can see in the macro definition, we have used different expressions based on the type of the argument x
. We use absi
if it is an integer value, and absd
if it is a double value. This feature is not new to C11, and you can...