Next: , Previous: Constructing Calls, Up: C Extensions

6.6 Referring to a Type with typeof



     typeof (x[0](1))


Here is an example with a typename as the argument:

     typeof (int *)

Here the type described is that of pointers to int.


A typeof construct can be used anywhere a typedef name can be used. For example, you can use it in a declaration, in a cast, or inside of sizeof or typeof.

The operand of typeof is evaluated for its side effects if and only if it is an expression of variably modified type or the name of such a type.

typeof is often useful in conjunction with statement expressions (see Statement Exprs). Here is how the two together can be used to define a safe “maximum” macro which operates on any arithmetic type and evaluates each of its arguments exactly once:

     #define max(a,b) \
           typeof (b) _b = (b); \
         _a > _b ? _a : _b; })


Some more examples of the use of typeof:

In GNU C, but not GNU C++, you may also declare the type of a variable as __auto_type. In that case, the declaration must declare only one variable, whose declarator must just be an identifier, the declaration must be initialized, and the type of the variable is determined by the initializer; the name of the variable is not in scope until after the initializer. (In C++, you should use C++11 auto for this purpose.) Using __auto_type, the “maximum” macro above could be written as:

     #define max(a,b) \
       ({ __auto_type _a = (a); \
           __auto_type _b = (b); \
         _a > _b ? _a : _b; })

Using __auto_type instead of typeof has two advantages:

Compatibility Note: In addition to typeof, GCC 2 supported a more limited extension that permitted one to write

     typedef T = expr;

with the effect of declaring T to have the type of the expression expr. This extension does not work with GCC 3 (versions between 3.0 and 3.2 crash; 3.2.1 and later give an error). Code that relies on it should be rewritten to use typeof:

     typedef typeof(expr) T;

This works with all versions of GCC.