_Generic
- C course
- Expert
- Lesson 26/47
- 5 min
Learn generic macros with _Generic.
The _Generic selection expression
_Generic is a compile-time construct introduced in C11. It selects different branches based on the type of an expression, giving you type-overload-like behavior.
Syntax: _Generic(expr, int: "int", double: "double", default: "other"). The compiler determines the expression's type and picks the matching branch. The default branch is used when no type matches. Combined with macros, _Generic becomes powerful: a single macro can behave differently for different types.
A _Generic macro example
A print_type macro can return the type name as a string via _Generic. #define print_type(x) printf("%s", _Generic((x), int: "int", double: "double", default: "other")).
Here (x) in parentheses makes the macro parameter safe. The _Generic result is a string; printf prints it with %s. Calling print_type(42) yields "int"; calling print_type(3.14) yields "double". This pattern is common in library design to build type-safe interfaces.
Practice Write the print_type macro
Write #define print_type(x) using _Generic: for int print "int", for double print "double", for default print "diğer" via printf("%s\n", ...). In int main(void) call print_type(42) and print_type(3.14).
Starter code
#include <stdio.h>
// print_type makrosunu _Generic ile yaz
// int ve double tiplerini yakala
// main'de makroyu int ve double ile çağırSample solution
#include <stdio.h>
#define print_type(x) printf("%s\n", _Generic((x), int: "int", double: "double", default: "diğer"))
int main(void) {
print_type(42);
print_type(3.14);
return 0;
}Expected output
int double
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the _Generic branch
_Generic(x, int: "int", ____: "diğer")
_Generic(x, int: "int", default: "diğer")
Explanation: The default branch is picked when no type matches.
2 When does _Generic branch?
- At run time, by looking at values
- At compile time, by looking at the type Correct answer
- At link time, by looking at symbols
- At load time, by looking at the address
Explanation: _Generic selects a branch at compile time based on the expression's type.
3 Match the _Generic branch
| Term | Meaning |
|---|---|
int: ... |
Integer branch |
double: ... |
Floating branch |
default: ... |
Catch-all branch |
char *: ... |
String branch |