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

Handling the `default` case in `_Generic`

Handling the default case in _Generic

What you'll learn: How to use the default keyword within a generic selection to ensure your code remains robust when it encounters unexpected data types.

The safety net for types

When you use _Generic to create a macro that acts differently based on a variable's type, you are essentially creating a compile-time "switch" statement. Just like a standard switch statement in C, if you don't account for a specific case, the program might fail to compile or behave unpredictably.

The default keyword acts as your safety net. It tells the compiler: "If the input type doesn't match any of the specific types I listed (like int, float, or char*), use this specific implementation instead."

Why use a default case?

Imagine you are building a universal "Print Value" macro. You might handle integers and strings explicitly, but what happens if someone passes a complex struct or a pointer to a custom object? Without a default case, the compiler will throw an error because it cannot find a match for that specific type.

By providing a default, you can gracefully handle unsupported types—perhaps by printing a generic "Unknown Type" message or triggering a static assertion to give the developer a clearer error message.

Seeing it in action

In the example below, we handle standard numbers, but we use the default case to catch everything else.

#include <stdio.h>

// A macro that identifies a type or returns a generic message
#define GET_TYPE_NAME(x) _Generic((x), \
    int: "This is an integer",         \
    float: "This is a float",          \
    double: "This is a double",        \
    default: "This is an unsupported type" \
)

int main() {
    int score = 95;
    double pi = 3.14159;
    char *name = "C-Programmer";

    printf("%d: %s\n", score, GET_TYPE_NAME(score));
    printf("%.2f: %s\n", pi, GET_TYPE_NAME(pi));
    
    // The char* is not explicitly handled, so it falls through to default
    printf("%s: %s\n", name, GET_TYPE_NAME(name));

    return 0;
}

Flexibility vs. Strictness

Using default makes your macros more flexible because they won't "break" the build if an unexpected type is passed. However, it is also a powerful tool for debugging. If you want to force a developer to explicitly handle every type, you might omit it. But in most library code, a default case is used to provide a fallback behavior, ensuring the code remains functional even as the project grows and new data types are introduced.

Key takeaway

The default keyword in a _Generic expression catches any type not explicitly listed, preventing compilation errors and providing a fallback path.