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

Limitations of C generics

Limitations of C generics

What you'll learn: Understanding why _Generic is a compile-time selection tool rather than a true dynamic dispatch or template system.

Not as "Generic" as you think

In languages like C++ or Java, generics allow the compiler to generate new code for different types or handle objects at runtime. In C, the _Generic keyword is essentially a "fancy switch statement" for the compiler. It looks at the type of a variable at compile time and picks one specific path.

The biggest limitation is that _Generic is strictly static. It cannot react to data that changes while your program is running. If you have a void* pointer that could point to either an int or a float, _Generic cannot "peek" inside to see what is there at runtime; it only sees the void* type and stops there.

The "All Code Must Compile" Trap

Unlike a C++ template, where code for a specific type is only generated if you use it, C requires every single expression inside a _Generic selector to be syntactically valid and type-correct—even the ones that aren't chosen.

Imagine you are building a "Universal Printer." You want it to print a string if given a char* and calculate the length if given an int.

#include <stdio.h>
#include <string.h>

void print_int(int check) { printf("Integer: %d\n", check); }
void print_str(char* check) { printf("String length: %zu\n", strlen(check)); }

#define universal_print(x) _Generic((x), \
    int: print_int(x),               \
    char*: print_str(x)              \
)

int main() {
    int val = 42;
    // This looks fine, but if print_str(x) expects a pointer, 
    // and you pass an int, some compilers will throw a warning 
    // or error even though that branch isn't chosen!
    universal_print(val); 
    return 0;
}

Because C evaluates the arguments before the macro fully expands, you can run into "type mismatch" errors for the branches the compiler didn't pick. This often forces you to use pointers for everything to keep the types consistent across all branches.

No Type Discovery

Lastly, _Generic cannot create new types. It can only choose from a list you manually provide. If you forget to add double to your macro, and someone passes a double, the program will simply fail to compile. It lacks the "write once, work for everything" automation found in modern high-level languages.

Key takeaway

_Generic performs compile-time type selection, meaning it cannot handle runtime data types and requires all potential branches to be compatible with the compiler's type-checking.