Please explain syntax rules and scope for "typedef"

ValenceElectron picture ValenceElectron · Mar 11, 2010 · Viewed 18.3k times · Source

What are the rules? OTOH the simple case seems to imply the new type is the last thing on a line. Like here Uchar is the new type:

typedef unsigned char Uchar;

But a function pointer is completely different. Here the new type is pFunc:

typedef int (*pFunc)(int);

I can't think of any other examples offhand but I have come across some very confusing usages.

So are there rules or are people just supposed to know from experience that this is how it is done because they have seen it done this way before?

ALSO: What is the scope of a typedef?

Answer

CB Bailey picture CB Bailey · Mar 11, 2010

Basically a typedef has exactly the same syntax as an object declaration except that it is prefixed with typedef. Doing that changes the meaning of the declaration so that the new identifier declares an alias for the type that the object that would have been declared, had it been a normal declaration, would have had.

A typedef is scoped exactly as the object declaration would have been, so it can be file scoped or local to a block or (in C++) to a namespace or class.

e.g.

Declares an int:

int a;

Declares a type that is an alias for int:

typedef int a_type;

Declares a pointer to a char:

char *p;

Declares an alias for a char *:

typedef char *pChar;

Declares a function pointer:

int (*pFn)(int);

Declares an alias for the type that is 'pointer to a function taking int and returning int':

typedef int (*pFunc)(int);