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

Type-based function overloading simulation

Type-based function overloading simulation

What you'll learn: How to use the _Generic keyword to make a single macro call act like different functions depending on the data type you pass in.

The Problem: C is Type-Strict

In many modern languages, you can have two functions with the same name (like print) that handle both integers and strings. In standard C, you can’t do this. You usually end up writing print_int(int x) and print_float(float x). This makes your code repetitive and forces you to remember a dozen different names for what is essentially the same action.

The Solution: The _Generic Selector

Introduced in C11, _Generic acts like a "switch statement" for types that runs at compile-time. It doesn't look at the value of a variable, but at its type. Think of it like a universal power adapter: you plug in your device, and the adapter identifies the plug shape to route the electricity correctly.

When you use _Generic, you provide a controlling expression (the variable you’re checking) and a list of type/result pairs.

Implementing the "Overload"

We typically wrap _Generic inside a #define macro. This allows the macro name to act as the "universal" function name.

#include <stdio.h>

// Specific functions for different types
void print_int(int i) { printf("Integer: %d\n", i); }
void print_dbl(double d) { printf("Double: %f\n", d); }
void print_str(char* s) { printf("String: %s\n", s); }

// The magic: A macro that selects the right function
#define smart_print(x) _Generic((x), \
    int: print_int,                  \
    double: print_dbl,               \
    char*: print_str,                \
    default: print_str               \
)(x)

int main() {
    int age = 25;
    double pi = 3.14;
    char* name = "C-Programmer";

    // The same macro name handles all three!
    smart_print(age);  // Calls print_int
    smart_print(pi);   // Calls print_dbl
    smart_print(name); // Calls print_str
    
    return 0;
}

How it works

In the code above, the compiler looks at smart_print(age). It sees that age is an int. It then looks at the _Generic list, finds the int: label, and replaces the macro with the print_int function. The final (x) at the end of the macro is what actually passes the argument to the selected function. If you pass a type not listed, the default: case kicks in.

This allows you to create clean, readable APIs that feel modern while maintaining C's low-level performance.

Key takeaway

The _Generic keyword allows you to simulate function overloading by mapping variable types to specific functions at compile-time.