HP C A.06.05 Reference Manual

Data Types and Declarations
Type Definitions Using typedef
Chapter 3 61
Type Definitions Using typedef
The typedef keyword, useful for abbreviating long declarations, allows you to create
synonyms for C data types and data type definitions.
Syntax
typedef-name
::=
identifier
Description
If you use the storage class typedef to declare an identifier, the identifier is a name for the
declared type rather than an object of that type. Using typedef does not define any objects or
storage. The use of a typedef does not actually introduce a new type, but instead introduces a
synonym for a type that already exists. You can use typedef to isolate machine dependencies
and thus make your programs more portable from one operating system to another.
For example, the following typedef defines a new name for a pointer to an int:
typedef int *pointer;
Instead of the identifier pointer actually being a pointer to an int, it becomes the name for
the pointer to the int type. You can use the new name as you would use any other type. For
example:
pointer p, *ppi;
This declares p as a pointer to an int and ppi as a pointer to a pointer to an int.
One of the most useful applications of typedef is in the definition of structure types. For
example:
typedef struct {
float real;
float imaginary;
} complex;
The new type complex is now defined. It is a structure with two members, both of which are
floating-point numbers. You can now use the complex type to declare other objects:
complex x, *y, a[100];
This declares x as a complex, y as a pointer to the complex type and a as an array of 100
complex numbers. Note that functions would have to be written to perform complex
arithmetic because the definition of the complex type does not alter the operators in C.