Difference between Declaration , Definition and Initialization in C++

Declaration, Definition and Initialization


Here, in this page we will discuss about the declaration, definition and initialization of a variable.

  • A variable is a memory unit that is capable of storing data which can be modified(rewritten) at any point of time in a program
  • Simply a variable is a name given to a memory location.
declaration, definition and initialization in C++

Declaring a variable 

  • A variable is created with a certain size(memory allocated) as per the data type specified, the variable must be declared before it is used and for storing data
  • In this  stage, garbage value is stored in the variable


int m,n,p;


int m;
int n;
int p;

Example program to demonstrate variable declaration 

#include <iostream>
using namespace std;
int m;//variable declaration
    cout<<"m value:"<<a<<endl;//garbage value
    cout<<"address of m:"<<&a<<endl;//a's assigned address
cout<<"size of m: "<<sizeof(a)<<"bytes";//allocated memory in bytes


m value:0
address of m:0x6ffe0c
size of m: bytes4


Variable Initialization 

In this stage, the user assigns value as per the requirement within the memory bounds i.e garbage value is overridden 



Example program to demonstrate variable initialization

#include <iostream>
using namespace std;
       int n;//variable declaration
       cout<<"n value:"<<n<<endl;
       n=10;//variable initialization
       cout<<"n value:"<<n<<endl;
       n=5+n;//data overriding
       cout<<"n value:"<<n<<endl;


Declaration cum initialization 

Variable can be initialized at the time of declaration itself 


int a=10;
int a,b,c=10;/* it careful: Only she is initialized with 10 and a and b e for uninitialized contains garbage values*/ 

Chained initialization 

Above program will raise an error because only ‘a’ has been declared ‘b’ and ‘c’ remain undeclared but still we have used as a part of initialization. hence we must be careful and ensure that all the variables are  declared before they have been used 


       int a=b=c=0;
       /* assignment operator evaluates from right to left


ERROR: 'a' was not declared 
ERROR: 'b'  was not declared 

To resolve the above declare a and b as follows 

int b,c;
int a=b=c=0;
Competitive Coding Techniques