The typeof operator


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. The alternate spelling of the keyword, __typeof__, is recommended. Given an expression e__typeof__(e) can be used anywhere a type name is needed, for example in a declaration or in a cast.


typeof construct itself is not an expression, but the name of a type. A typeof construct behaves like a type name defined using typedef, although the syntax resembles that of sizeof.
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
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; }

Comments

  1. Wow... Is it defined in the standards, and is portable. I would luv to find out the implementation of typeof.

    Thanks!

    ReplyDelete

Post a Comment

Popular posts from this blog