Consider this thought experiment, to clarify the difference between declaration and definition:
You have a data structure, a network or graph, consisting of two different types of nodes.
Each node type can refer to four nodes of the same type, and two nodes of the different type.
How do you define the structures? When you define the first one, the other one is still undefined, so how do you refer to that?
We do that by
declaring the structures before we define them:
struct one;
struct two;
struct one {
struct one *ones[4];
struct two *twos[2];
// Contents of the node omitted
};
struct two {
struct two *twos[4];
struct one *ones[2];
// Contents of the node omitted
};
We can do the same by
defining the two node types first (
node_one and
node_two, becoming new variable types) based on as yet undefined structure types, which also declares the structure types:
typedef node_one struct one;
typedef node_two struct two;
struct one {
node_one *ones[4];
node_two *twos[2];
// Contents of the node omitted
};
struct two {
node_two *twos[4];
node_one *ones[2];
// Contents of the node omitted
};
Similarly, we can declare a function before we define it, so that two functions can call each other.
The C standard defines declaration and definition in for example C11 6.5p5 as
A declaration specifies the interpretation and attributes of a set of identifiers.
A definition of an identifier is a declaration for that identifier that:
— for an object, causes storage to be reserved for that object;
— for a function, includes the function body;
— for an enumeration constant, is the (only) declaration of the identifier;
— for a typedef name, is the first (or only) declaration of the identifier.