Typeof operator in C (Re: An Interesting View of "Strong" Vs. "Weak" Typing)

Ted Dunning ted at nmsu.edu
Sun Jan 14 06:59:41 AEST 1990


In article <-K016ODxds13 at ficc.uu.net> peter at ficc.uu.net (Peter da Silva) writes:

   But a typeof operator... wouldn't that be something...

   #define SWAP(a,b) {typeof a tmp; tmp=a; a=b; b=tmp}

from the documentation for the gcc extensions:

----------------------------------------------------------------
File: gcc  Node: Typeof, Prev: Naming Types, Up: Extensions, Next: Lvalues

Referring to a Type with `typeof'
=================================

Another way to refer to the type of an expression is with `typeof'.
The syntax of using of this keyword looks like `sizeof', but the
construct acts semantically like a type name defined with `typedef'.

There are two ways of writing the argument to `typeof': with an
expression or with a type.  Here is an example with an expression:

     typeof (x[0](1))

This assumes that `x' is an array of functions; the type described
is that of the values of the functions.

Here is an example with a typename as the argument:

     typeof (int *)

Here the type described is that of pointers to `int'.

If you are writing a header file that must work when included in ANSI C
programs, write `__typedef' instead of `typedef'.
*Note Alternate Keywords::.

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

   * This declares `y' with the type of what `x' points to.

          typeof (*x) y;

   * This declares `y' as an array of such values.

          typeof (*x) y[4];

   * This declares `y' as an array of pointers to characters:

          typeof (typeof (char *)[4]) y;

     It is equivalent to the following traditional C declaration:

          char *y[4];

     To see the meaning of the declaration using `typeof', and why it
     might be a useful way to write, let's rewrite it with these macros:

          #define pointer(T)  typeof(T *)
          #define array(T, N) typeof(T [N])

     Now the declaration can be rewritten this way:

          array (pointer (char), 4) y;

     Thus, `array (pointer (char), 4)' is the type of arrays of 4
     pointers to `char'.

--
She gave us wine, and set before us a dish composed of red pepper,
ground and mixed with corn meal, stewed in fat and water.  We could
not eat it.

  -- a kentucky mountain man's reaction to new mexican cuisine in the
     early 1800's.



More information about the Comp.lang.c mailing list