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

Using `typeof` in C23

Using typeof in C23

What you'll learn: How to use the typeof operator to declare variables based on existing types without needing to name them manually.

The "Rubber Stamp" Shortcut

In older versions of C, if you wanted to create a new variable that matched the type of an existing one, you had to know exactly what that type was. If you changed a variable from an int to a long, you had to hunt through your code and manually update every related declaration.

C23 introduces typeof, which acts like a "rubber stamp." Instead of looking up a type, you tell the compiler: "Whatever type this specific thing is, make my new variable the same."

How it Works

The typeof operator takes an expression or a type name and evaluates to that type at compile-time. It doesn't actually run the code inside the parentheses; it just inspects it.

Imagine you have a complex function that returns a specific pointer type. Rather than typing out a long, messy pointer declaration, you can just use typeof.

#include <stdio.h>

int main() {
    double salary = 55000.50;

    // "Look at salary and give me that type"
    typeof(salary) bonus; 
    
    // bonus is now a double
    bonus = salary * 0.10;

    int x = 10;
    int y = 20;
    
    // You can even use expressions
    typeof(x + y) result = 0; 
    
    printf("Bonus: %.2f\n", bonus);
    return 0;
}

Why This Matters for Advanced C

As you move into advanced C, you will encounter complex structures and pointers to functions. Writing int (*(*f)(int, int))(int) is a headache. typeof simplifies this by allowing you to mirror existing structures.

It is particularly powerful when writing macros. If you are writing a generic macro to swap two values, you can use typeof to create a temporary variable that automatically matches the type of the arguments passed in. This makes your code more "polymorphic" (able to handle multiple types) while remaining strictly type-safe.

Key takeaway

typeof allows you to declare variables by referencing the type of an existing expression, making your code more flexible and easier to maintain.