Course contentsShow
← C
Lesson 979 of 1,21913. Advanced CFree lesson

Mathematical macros using `_Generic`

Mathematical macros using _Generic

What you'll learn: How to create a single macro that automatically chooses the correct math function based on whether you pass it a float, double, or long double.

The Problem of Function Overloading

In languages like C++, you can have multiple functions with the same name as long as the arguments are different types. In standard C, every function name must be unique. This is why the math library (math.h) gives us three versions of the absolute value function: fabsf() for floats, fabs() for doubles, and fabsl() for long doubles.

Remembering which suffix belongs to which type is a chore. It makes your code brittle; if you change a variable from a float to a double, you have to hunt down every function call associated with it and rename it.

The Type-Switching Macro

Introduced in C11, the _Generic keyword acts like a compile-time "switch" statement based on the type of an expression. It allows us to map types to specific functions. When the compiler sees the macro, it looks at the type of the variable you provided and swaps the macro for the specific function name you mapped to it.

Think of it like a universal charging cable with interchangeable tips. You have one cable (the macro), but the end piece (the function) automatically swaps out depending on whether you plug in a phone, a tablet, or a laptop.

Implementation Example

Here is how you create a "generic" square root macro that works for all floating-point types:

#include <stdio.h>
#include <math.h>

// The _Generic keyword selects the right function at compile-time
#define generic_sqrt(x) _Generic((x), \
    float: sqrtf,                     \
    long double: sqrtl,               \
    default: sqrt                     \
)(x)

int main() {
    float f = 9.0f;
    double d = 16.0;
    long double ld = 25.0L;

    // We use the same macro name for all three types!
    printf("Float: %f\n", generic_sqrt(f));
    printf("Double: %f\n", generic_sqrt(d));
    printf("Long Double: %Lf\n", generic_sqrt(ld));

    return 0;
}

In this code, the _Generic block evaluates the type of x. If x is a float, it returns the function pointer for sqrtf. The (x) at the very end of the macro definition then calls whichever function was selected.

Key takeaway

_Generic allows you to write "overloaded" macros that provide a single, clean interface for type-specific functions, making your mathematical code more readable and easier to maintain.