Saturday, June 25, 2011

What is the difference between variable definition and declaration?

A variable is defined when the compiler allocates storage space for it, and this occurs only once in the source code.

e.g. int a 

In contrast, a programmer can declare a variable several times. It does not allocate any storage space. It just introduces an identifier and a type.

e.g. extern int a

Having a declaration is sufficient for the compilation process. However, the linking stage will fail if the variable is not defined or if it is defined twice.

It should be noted that when a variable is defined, it automatically gets declared at that location. Thus, first example - int a - both defines and declares the variable a.


No comments: