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

Comparing `_Generic` to C++ templates

Comparing _Generic to C++ templates

What you'll learn: The fundamental differences between C’s compile-time type selection and C++’s code-generation templates.

If you have ever dabbled in C++, you have likely seen templates. They allow you to write a single function, like sort<T>, and the compiler automatically generates a new version for every data type you use. In C, the _Generic keyword might look like a template at first glance, but it works very differently under the hood.

Selection vs. Generation

The biggest difference is that _Generic does not "create" new code; it acts like a traffic controller. When you use a template in C++, the compiler is an architect that builds a new house for every specific material (int, float, char) you provide. In C, _Generic is simply a map that points to houses you have already built.

With _Generic, you must manually write every function variation yourself. The macro then simply picks the right one based on the type of the variable you pass in.

#include <stdio.h>

// You must manually define every variation
void print_int(int i) { printf("Integer: %d\n", i); }
void print_float(float f) { printf("Float: %f\n", f); }

// _Generic acts as a selector, NOT a generator
#define print_val(x) _Generic((x), \
    int: print_int,            \
    float: print_float         \
)(x)

int main() {
    print_val(10);    // Becomes print_int(10)
    print_val(3.14f); // Becomes print_float(3.14f)
    return 0;
}

The "Closed" vs. "Open" System

C++ templates are "open-ended." If a library author writes a template, you can use it with a custom struct you created today, and the compiler will generate the logic for you.

C’s _Generic is a "closed" system. If the print_val macro above wasn't written to handle your custom struct, you cannot use it. You would have to go back and edit the macro definition to include your new type.

Performance and Binary Size

Because _Generic just maps to existing functions, it provides a very predictable binary size. C++ templates can lead to "code bloat," where the compiler generates hundreds of nearly identical functions, significantly increasing the size of your program. In C, what you see is what you get—if you didn't write the function, it doesn't exist.

Key takeaway

C++ templates generate new code for any type automatically, while C’s _Generic simply selects from a pre-defined list of functions you wrote manually.