Wednesday, 22 January 2014

Forward Declaration of Structures

Forward Declaration:
   
Forward declaration is a declaration proceeding an actual definition, usually for the purpose of being able to reference the declared type when the definition is not available.

Of course, not everything may be done with the declared-not-defined structure, but in certain context it is possible to use it.

Such type is called incomplete, and there are a number of restrictions on its usage.

For example:

struct X; // forward declaration

void f(struct X*) { }  // usage of the declared, undefined structure

// void f(struct X) { }         // ILLEGAL
// struct X x;                  // ILLEGAL
// int n =sizeof(struct X);     // ILLEGAL

// later, or somewhere else altogether
struct X { /* ... */ };

This can be useful (e.g.) to break circular dependencies, or cut down the compilation time, as the definitions are usually significantly larger, and so more resources are required to parse it.

No comments: