Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Keywords and Statements

The typeof operators

Reference for C23 typeof and typeof_unqual: name the type of an expression, write safe generic macros, and how qualifiers and arrays are handled.

typeof was a GNU extension for decades and became standard in C23. It names the type of an expression (or of a type name) so you can use it anywhere a type is expected: to declare variables, as a cast target, or inside macros. typeof_unqual does the same but drops qualifiers such as const, volatile, restrict and _Atomic.

The main use is writing type-generic macros that evaluate their arguments once, such as MAX and SWAP. The operand of typeof is not evaluated (unless it is a variable length array type).

C
int n = 5;
typeof(n) m = 7;            /* int */
typeof_unqual(const int) k; /* int */

Try it

C Declaring variables with typeof

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Safe generic macros

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The statement-expression ({ ... }) used for MAX is a GCC and Clang extension, not part of standard C. SWAP uses only standard C23.

Syntax

C
typeof(expression)
typeof(type-name)
typeof_unqual(expression)
typeof_unqual(type-name)
Form Description
typeof(e) The type of e, with qualifiers kept.
typeof_unqual(e) The type of e without const, volatile, restrict and _Atomic.
typeof(T) The type T. Useful to make a type from a macro argument.

Returns: a type specifier, not a value.

Errors: the operand cannot be a bit-field member. The operand is not evaluated, so side effects such as i++ do not happen.

Usage notes

  • Arrays stay arrays. typeof(arr) for int arr[4] is int[4], not a pointer.
  • Qualifier trap. typeof(x) keeps const, so typeof(x) copy; without an initializer fails for a const x. Use typeof_unqual for working variables.
  • Typedefs. typedef typeof(expr) T; is an easy way to name an expression's type.
  • Compared with auto. auto infers a variable's type from its initializer; typeof names a type you can reuse and apply in casts and parameter lists.
  • Macros. Evaluate each argument once into a typeof temporary, as SWAP does, to avoid double evaluation.
  • Older compilers. GCC and Clang accept __typeof__ in every mode, including pre-C23.
  • Variably modified types. If the operand's type is a VLA type, the operand is evaluated.