HP 3000 Manuals

Type Definitions Using typedef [ HP C/iX Reference Manual ] MPE/iX 5.0 Documentation


HP C/iX Reference Manual

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.

Other type specifiers (void, char, short, int, long, signed, unsigned,
float, and double) cannot be used with a name declared by typedef.  For
example, the following typedef usage is illegal:

     typedef long int li;
        .
        .
        .
     unsigned li x;

typedef identifiers occupy the same name space as ordinary identifiers
and follow the same scoping rules.

Structure definitions which are used in typedef declarations can also
have structure tags.  These are still necessary to have self-referential
structures and mutually referential structures.

Example 

     typedef unsigned long ULONG;  /* ULONG is an unsigned long */
     typedef int (*PFI)(int);  /* PFI is a pointer to a function */
       /* taking an int and returning an int */

     ULONG v1; /* equivalent to "unsigned long v1" */
     PFI v2; /* equivalent to "int (*v2)(int)"   */



MPE/iX 5.0 Documentation