C _Generic Keyword
Example
Use _Generic in a macro to get the name of a type:
#define typeName(x) _Generic((x), int: "int", double: "double", default: "other")
int main() {
int myNum = 15;
double myDoubleNum = 19.99;
printf("%s\n", typeName(myNum));
printf("%s", typeName(myDoubleNum));
return 0;
}
Definition and Usage
The _Generic keyword selects one of several expressions, based on the type of a value. The choice is made when the program is compiled, not when it runs.
First write the value, then a list of type: expression pairs. The default: expression is used when no type matches.
It is almost always used inside a #define macro, so that one macro name can work with values of different types.
Related Pages
Read more about #define macros in our C Macros Tutorial.