4.10 Declaring Type Definitions

In a declaration whose storage-class specifier is typedef , each declarator defines a typedef name that specifies an alias for the stated type. A typedef declaration does not introduce a new type, but only introduces a synonym for the stated type. For example:

typedef int integral_type;
integral_type x;

In the previous example, integral_type is defined as a synonym for int , and so the following declaration of x declares x to be of type int . Type definitions are useful in cases where a long type name (such as some forms of structures or unions) benefits from abbreviation, and in cases where the interpretation of the type can be made easier through a type definition.

A typedef name shares the same name space as other identifiers in ordinary declarators. If an object is redeclared in an inner scope, or is declared as a member of a structure or union in the same or inner scope, the type specifiers cannot be omitted from the inner declaration. For example:

typedef signed int t;
typedef int plain;
struct tag {
   unsigned t:4;
   const t:5;
   plain r:5;
};

It is evident that such constructions are obscure. The previous example declares a typedef name t with type signed int , a typedef name plain with type int , and a structure with three bit-field members, one named t , another unnamed member, and a third member named r . The first two bit-field declarations differ in that unsigned is a type specifier, which forces t to be the name of a structure member by the rule previously given. The second bit- field declaration includes const , a type qualifier, which only qualifies the still-visible typedef name t .

The following example shows additional uses of the typedef keyword:

typedef int miles, klicksp(void);
typedef struct { double re, im; } complex;
   .
   .
   .
miles distance;
extern klicksp *metricp;
complex x;
complex z, *zp;

All of the code shown in the previous example is valid. The type of distance is int , the type of metricp is a pointer to a function with no parameters returning int , and the type of x and z is the specified structure. zp is a pointer to the structure.

It is important to note that any type qualifiers used with a typedef name become part of the type definition. If the typedef name is later qualified with the same type qualifier, an illegal construction results. For example:

typedef const int x;
const x y;            /*  Illegal -- duplicate qualifier used  */


Previous Page | Next Page | Table of Contents | Index