Introduction to the _Generic keyword
What you'll learn: How to use C’s type-generic expressions to make a single macro behave differently based on the data type passed to it.
The Problem: Type Rigidity
In C, functions are strict. If you write a function to square an integer, it won’t work for a double. You end up writing square_int(), square_float(), and square_double(). This is repetitive and makes your code messy.
Imagine a vending machine that only accepts one specific coin size per slot. To buy a snack, you have to find the exact slot that fits a dime, then another for a quarter. Wouldn't it be easier if there was one "universal" slot that recognized the coin and handled it automatically? That is what _Generic does for your code.
How _Generic Works
Introduced in C11, _Generic isn't a function; it's a compile-time "selector." It looks at the type of a variable and picks a specific piece of code to run. It acts like a switch statement, but instead of checking the value of a variable, it checks the type.
Here is how you define a universal "Print Type" macro:
#include <stdio.h>
#define print_type(x) _Generic((x), \
int: "this is an integer", \
float: "this is a float", \
char*: "this is a string", \
default: "unknown type" \
)
int main() {
int score = 10;
float pi = 3.14f;
char* name = "C Programming";
printf("Score: %s\n", print_type(score));
printf("Pi: %s\n", print_type(pi));
printf("Name: %s\n", print_type(name));
return 0;
}
Why This Matters
When the compiler sees print_type(score), it notices score is an int. It then literally replaces that macro call with the string "this is an integer" before the program even runs.
This allows you to create "Generic Macros." You can create a single macro called calculate() that calls a math function for integers or a completely different one for floats, all while keeping your main code clean and readable. You get the power of "polymorphism" (one interface, many types) without the overhead of complex C++ features.
Key takeaway
The _Generic keyword allows you to map different types to specific expressions at compile-time, providing a way to write flexible, type-aware code.