Open In App

Difference between Definition and Declaration

Last Updated : 30 Oct, 2023
Like Article

Declaration of a variable is for informing the compiler of the following information: name of the variable and the type of the value it will hold i.e., declaration gives details about the properties of a variable. Whereas, in the Definition of a variable, memory is allocated for 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 statement,

int a;

Here, the information such as the variable name: a, and data type: int, is sent to the compiler which will be stored in the data structure known as the symbol table. Along with this, a memory of size 4 bytes(depending upon the type of compiler) will be allocated. Suppose, if we want to only declare variables and not define them 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 name and type 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 a different file.

Declaration of a function provides the compiler with 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 as follows: 

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 during definition.
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.

In declaration, the data type and name of the variable is known In definition, value stored in the variable is also known.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads