What is the difference between declaring a variable and defining a variable? Explain with the help of example
Answers
Explanation:
Declaration of a variable is for informing to the compiler the following information: name of the variable, type of value it holds and the initial value if any it takes. i.e., declaration gives details about the properties of a variable. Whereas, Definition of a variable says where the variable gets stored. i.e., memory for the variable is allocated during the definition of the variable.
In C language definition and declaration for a variable takes place at the same time. i.e. there is no difference between declaration and definition. For example, consider the following declaration
int a;
Here, the information such as the variable name: a, and data type: int, which is sent to the compiler which will be stored in the data structure known as symbol table. Along with this, a memory of size 2 bytes(depending upon the type of compiler) will be allocated.
Suppose, if we want to only declare variables and not to define it i.e. we do not want to allocate memory, then the following declaration can be used
extern int a;
In this example, only the information about the variable is sent and no memory allocation is done. The above information tells the compiler that the variable a is declared now while memory for it will be defined later in the same file or in different file.
Declaration of a function provides the compiler the name of the function, the number and type of arguments it takes and its return type. For example, consider the following code,
int add(int, int);
Here, a function named add is declared with 2 arguments of type int and return type int. Memory will not be allocated at this stage.
Definition of the function is used for allocating memory for the function. For example consider the following function definition,
int add(int a, int b)
{
return (a+b);
}
During this function definition, the memory for the function add will be allocated. A variable or a function can be declared any number of times but, it can be defined only once.
The above points are summarized in the following table,
Declaration Definition
A variable or a function can be declared any number of times A variable or a function can be defined only once
Memory will not be allocated during declaration Memory will be allocated
int f(int);
The above is a function declaration. This declaration is just for informing the compiler that a function named f with return type and argument as int will be used in the function.
int f(int a)
{
return a;
}
The system allocates memory by seeing the above function definition.