typedef Specifier

The typedef specifier defines a name that can be used as a synonym for a type or derived type. You cannot use the typedef specifier inside a function definition.

Syntax

typedef-name:

identifier

A typedef declaration introduces a name that, within its scope, becomes a synonym for the type given by the decl-specifiers portion of the declaration. In contrast to the class, struct, union, and enum declarations, typedef declarations do not introduce new types — they introduce new names for existing types.

One use of typedef declarations is to make declarations more uniform and compact. For example:

typedef char CHAR;          // Character type.
typedef CHAR * PSTR;        // Pointer to a string (char *).
...
PSTR strchr( PSTR source, CHAR target );

The names introduced by the preceding declarations are synonyms for:

Name Synonymous Type
CHAR
char
PSTR
char *

The preceding example code declares a type name, CHAR, which is then used to define the derived type name PSTR (a pointer to a string). Finally, the names are used in declaring the function strchr. To see how the typedef keyword can be used to clarify declarations, contrast the preceding declaration of strchr with the following declaration:

char * strchr( char * source, char target );

To use typedef to specify fundamental and derived types in the same declaration, you can separate declarators with commas. For example:

typedef char CHAR, *PSTR;

A particularly complicated use of typedef is to define a synonym for a “pointer to a function that returns type T.” For example, a typedef declaration that means “pointer to a function that takes no arguments and returns type void” uses this code:

typedef void (*PVFN)();

The synonym can be handy in declaring arrays of functions that are to be invoked through a pointer:

#include <iostream.h>
#include <stdlib.h>

extern void func1();         // Declare 4 functions.
extern void func2();         // These functions are assumed to be
extern void func3();         //  defined elsewhere.
extern void func4();
                             // Declare synonym for pointer to
typedef void (*PVFN)();      //  function that takes no arguments
                             //  and returns type void.

void main( int argc, char * argv[] )
{
    // Declare an array of pointers to functions.
    PVFN pvfn1[] = { func1, func2, func3, func4 };

    // Invoke the function specified on the command line.
    if( argc > 0 && *argv[1] > '0' && *argv[1] <= '4' )
   (*pvfn1[atoi( argv[1] ) - 1])();
}