23B. Forward and Recursive Structure Type Definitions


Forward declarations

Normally, a structure type needs to be defined before you use it. But there are times when you need to refer to a structure type before its definition. In that case, use a forward declaration of the type, which is just the type heading followed by a semicolon. For example,

  struct Cell;
is a forward declaration for type Cell.

Forward declarations have a rather severe limitation. A forward declaration of type Cell allows you to use type Cell* before you define type Cell. But it does not allow you to use type Cell without a * before the definition of type Cell.


Recursive structure type definitions

A definition of structure type T can refer to type T* without a forward declaration. For example, type definition

  struct ListCell
  {
    ListCell* next;
    int       item;
  };
indicates that a value of type ListCell has two fields, one of which is a pointer to a ListCell. We will see uses of this when looking at data structures. It will also help to illustrate structure copying, which is next.


Exercises

  1. Can a definition of structure type Kangaroo contain a field of type Kangaroo? Answer

  2. What is the purpose of a forward declaration of a structure type? Answer