HP C A.06.05 Reference Manual
Data Types and Declarations
Structure and Union Specifiers
Chapter 3 51
Another use for structure tags is to write self-referential structures. A structure of type S may
contain a pointer to a structure of type S as one of its members. Note that a structure can
never have itself as a member because the definition of the structure's content would be
recursive. A pointer to a structure is of fixed size, so it may be a member. Structures that
contain pointers to themselves are key to most interesting data structures. For example, the
following is the definition of a structure that is the node of a binary tree:
struct node {
float data; /* data stored at the node */
struct node *left; /* left subtree */
struct node *right; /* right subtree */
};
This example defines the shape of a node type of structure. Note that the definition contains
two members (left and right) that are themselves pointers to structures of type node.
The C programming rule that all objects must be defined before use is relaxed somewhat for
structure tags. A structure can contain a member that is a pointer to an as yet undefined
structure. This allows for mutually referential structures:
struct s1 { struct s2 *s2p; };
struct s2 { struct s1 *s1p; };
In this example, structure s1 references the structure tag s2. When s1 is declared, s2 is
undefined. This is valid.
Example
struct tag1 {
int m1;
int :16; /* unnamed bit-field */
int m2 :16; /* named bit-field; packed into
/* same word as previous member */
int m3, m4;
}; /* empty declarator list */
union tag2 {
int u1;
int :16;
int u2:16; /* bit-field, starts at offset 0 */
int u3, u4;
} fudge1, fudge2; /* declarators denoting objects of the union type */
struct tag1 obj1, obj2; /* use of type "struct tag1", */
/* whose body has been declared above */