The typedef
facility is used to create aliases for types. For example,
typedef int *iptr;
creates the name iptr
as a synonym for the type int *
, so you could declare pointers using
iptr p, q;
instead of writing
int *p, *q;
C declaration syntax is a bit more complicated than most people realize, especially where pointers are involved. The basic rules are:
T *p; // p is a pointer to T
T *a[N]; // a is an array of pointer to T
T *f(); // f is a function returning pointer to T
T (*a)[N]; // a is a pointer to an array of T
T (*f)(); // f is a pointer to a function returning T
T const *p; // p is a pointer to const T
const T *p; // same as above
T * const p; // p is a const pointer to T
Things can get arbitrarily complicated - you can have arrays of pointers to functions:
T (*a[N])();
or functions returning pointers to arrays:
T (*f())[N];
or even worse atrocities. Function pointer declarations get uglier when there are parameters in the mix; fortunately, you only need to list the parameter types in a declaration, not the names:
typedef Value (*NativeFn)(int, Value*);
makes things a little easier to follow.
That declaration creates NativeFn
as a synonym for the type "pointer to function taking an int
and Value *
and returning Value
".
Suppose you have a function defined as
Value foo( int argcCount, Value *args )
{
Value result;
...
return result;
}
If you want to create a pointer to this function named fptr
, you'd normally declare it as
Value (*fptr)(int, Value *) = foo;
However, the typedef
declaration above allows you to write
NativeFn fptr = foo;
Having said all that, use typedef
sparingly. The problem is that while it can create an easier-to-read ways of declaring some items, it also hides some potentially useful information. For example, despite the iptr
example above, it's best to not hide pointers behind typedefs - if someone needs to use the unary *
operator on p
or q
in order to use them properly, than that information needs to be in the declaration of those items. If someone ever needs to call the thing fptr
points to, then they need to know what the return type is, the number and types of parameters, etc., but all that information is missing in the declaration that uses the typedef name.