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).
int n = 5; typeof(n) m = 7; /* int */ typeof_unqual(const int) k; /* int */
Try it
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.
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
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)forint arr[4]isint[4], not a pointer. - Qualifier trap.
typeof(x)keepsconst, sotypeof(x) copy;without an initializer fails for aconst x. Usetypeof_unqualfor working variables. - Typedefs.
typedef typeof(expr) T;is an easy way to name an expression's type. - Compared with
auto.autoinfers a variable's type from its initializer;typeofnames a type you can reuse and apply in casts and parameter lists. - Macros. Evaluate each argument once into a
typeoftemporary, asSWAPdoes, 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.