The typeof operator (IBM extension)
The typeof
operator returns the type
of its argument, which can be an expression or a type. The language
feature provides a way to derive the type from an expression. Given
an expression e
, __typeof__(e)
can
be used anywhere a type name is needed, for example in a declaration
or in a cast. The alternate spelling of the keyword, __typeof__
,
is recommended.
The following examples illustrate its basic syntax. For
an expression
e
: int e;
__typeof__(e + 1) j; /* the same as declaring int j; */
e = (__typeof__(e)) f; /* the same as casting e = (int) f; */
Using a
typeof
construct is equivalent
to declaring a typedef
name. Given typedef
int T[2];
int i[2];
you can write __typeof__(i) a; /* all three constructs have the same meaning */
__typeof__(int[2]) a;
__typeof__(T) a;
The behavior of the code is as if you
had declared int a[2];
. For a bit field, typeof
represents the
underlying type of the bit field. For example, int m:2;
,
the typeof(m)
is int
. Since the
bit field property is not reserved, n
in typeof(m)
n;
is the same as int n
, but not int
n:2
.
The
typeof
operator can be nested inside sizeof
and
itself. The following declarations of arr
as an array
of pointers to int
are equivalent: int *arr[10]; /* traditional C declaration */
__typeof__(__typeof__ (int *)[10]) a; /* equivalent declaration */
The
typeof
operator can be useful in
macro definitions where expression e
is a parameter.
For example, #define SWAP(a,b) { __typeof__(a) temp; temp = a; a = b; b = temp; }
Notes:
- The
typeof
and__typeof__
keywords are supported as follows:- The
__typeof__
keyword is recognized in C under LANGLVL(EXTC89| EXTC99|EXTENDED), and in C++ under the LANGLVL(EXTENDED). - The
typeof
keyword is only recognized when the KEYWORD(TYPEOF) compiler option is in effect.
- The