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

Implementing a generic 'Print' macro

Implementing a generic 'Print' macro

What you'll learn: How to use the _Generic keyword to create a single macro that automatically selects the correct format specifier for different data types.

The Problem: Type Rigidity

In C, the printf function is notoriously picky. If you want to print an integer, you must remember %d. For a float, it’s %f. For a string, %s. If you accidentally pass a double to a %d specifier, the compiler might stay silent, but your output will be gibberish. In modern programming, we often want a single "Print" command that is smart enough to figure out the type for us—a feature known as ad-hoc polymorphism.

The Solution: The _Generic Selector

Introduced in C11, _Generic acts like a compile-time switch statement based on the type of an expression rather than its value. It allows us to map a variable's type to a specific function or string.

Think of _Generic as a specialized vending machine. You drop in a variable, and the machine looks at the "shape" of the data. If it’s an int, it gives you one result; if it’s a char*, it gives you another.

Building the Macro

We can combine _Generic with a macro to create a universal print() function. The macro will evaluate the type of the argument at compile-time and pick the correct printf call.

#include <stdio.h>

// The macro chooses the right function based on the type of 'x'
#define print(x) _Generic((x), \
    int:          printf("%d\n", x), \
    double:       printf("%f\n", x), \
    const char*:  printf("%s\n", x), \
    default:      printf("Unknown type\n") \
)

int main() {
    int age = 25;
    double pi = 3.14159;
    const char* greeting = "Hello, C!";

    // One command to rule them all
    print(age);      // Compiles to printf("%d\n", age)
    print(pi);       // Compiles to printf("%f\n", pi)
    print(greeting); // Compiles to printf("%s\n", greeting)

    return 0;
}

How it works

When the compiler sees print(age), it checks the type of age. Because age is an int, the _Generic expression resolves specifically to the printf("%d\n", x) branch. The other branches are discarded entirely. This happens before the program even runs, meaning there is zero performance penalty compared to calling printf manually.

This pattern makes your code cleaner and reduces the "mental tax" of remembering format specifiers for every single variable you want to inspect.

Key takeaway

The _Generic keyword enables compile-time type dispatching, allowing you to create flexible, "type-aware" macros that simplify your API.