Jan 3, 2016

C Programming #56: Structure - forward declaration

Forward declaration is used in place when structure contents is still unknown.


Classic example would be the declaration of node in linked list. Each node in a linked list contains (member variable)

  1. val associated with node
  2. pointer to next node.

First member variable declaration is straight forward.  But when it comes to second member variable it is pointer to structure which we are presently declaring. In such cases forward declaration could be used. Note that most of the modern compiler work just fine without this forward declaration too.

// Forward declaration
struct node;

// node structure declaration
struct node {  
  int val;
  struct node *next;
};

Including typedef it can be done as follows.

// Forward declaration
typedef struct node node_t;

// node structure declaration
struct node {
  int val;
  node_t *next;
};

Links

Next Article - C Programming #57: Structure - partial initialization
Previous Article - C Programming #55: Structure declaration and definition
All Article - C Programming

No comments :

Post a Comment