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

The syntax of a generic selection

The syntax of a generic selection

What you'll learn: How to use the _Generic keyword to make your code behave differently based on the data type of a variable.

The "Type-Sensitive" Vending Machine

Imagine a vending machine where the buttons don't have labels like "Cola" or "Water." Instead, the machine looks at the coin you insert. If you drop in a gold coin, it gives you champagne; if you drop in a silver coin, it gives you soda; if it’s copper, you get water.

In C, _Generic acts like this machine. It allows you to write one piece of code that "chooses" a specific path based on the type of a variable at compile-time. This is the secret sauce behind creating functions that feel like they are overloaded, similar to languages like C++ or Java.

Breaking Down the Syntax

The syntax for a generic selection looks a bit like a switch statement, but it works on types rather than values. Here is the basic structure:

_Generic(expression, 
    type1: result1, 
    type2: result2, 
    default: default_result
)
  1. The Controlling Expression: This is the variable or value you want to check.
  2. The Association List: A list of pairs where you say, "If the expression is this type, do this."
  3. The Default: A fallback option if the type doesn't match any of your specific cases.

A Practical Example

Usually, we wrap _Generic inside a macro to make it easy to use. Let’s say we want a single name, print_value, that works for both integers and strings.

#include <stdio.h>

// The macro selects the correct function name based on the type of 'x'
#define print_value(x) _Generic((x), \
    int: print_int,                  \
    char*: print_str,                \
    default: print_unknown           \
)(x)

void print_int(int i) { printf("It's an integer: %d\n", i); }
void print_str(char* s) { printf("It's a string: %s\n", s); }
void print_unknown() { printf("Unknown type!\n"); }

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

    print_value(age);   // Resolves to print_int(age)
    print_value(name);  // Resolves to print_str(name)
    print_value(pi);    // Resolves to print_unknown()
    
    return 0;
}

Notice the (x) at the very end of the macro definition. The _Generic part evaluates to a function name, and that final (x) actually calls the function that was selected.

Key takeaway

The _Generic keyword evaluates the type of an expression at compile-time to select a corresponding value or function from a predefined list.