Variable in C++

Variable are used to hold the value.We can change the value of a variable depending on the information of the program.They are not fixed.Variables are declared to be of a type.So, when we declare a variable then we use datatype like integer,float etc.These datatype show that the variable hold the integer or float value.

The name of a variable can be in letters, digits, and the underscore character. It must begin with either a letter or an underscore. C++ is case-sensitive.So, Upper and Lowercase letters are distinct.Some valid declarations are :

int    a,b,c;

char   ch1, ch2;

float  f1, salary;

double d,g;


The line int a,b,c; both declares and defines the variables a,b and c; which instructs the compiler to create variables named a,b and c of type int.

Variables can be initialized  in their declaration. The initializer consists of an equal sign followed by a constant expression as follows:

type variable_name = value;

Some examples are:

extern int a=6, b=7;    // declaration of a and b.

int a=6, b=7;           // definition and initializing d and f.

byte m = 12;                // definition and initializes m.

char y = ‘y’;               // the variable y has the value ‘y’.

Variable Declaration in C++:

Before a variable is used in a program, we must declare it. This activity enables the compiler to make available the appropriate type of location in the memory.A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program.

int rollno;

You can declare more than one variable of same type in a single single statement

int  a,b;

Initialization of variable in c++:

When we declare a variable it’s default value is undetermined. We can declare a variable with some initial value.

int a = 20;


Try the following example where a variable has been declared at the top, but it has been defined inside the main function:

#include <iostream.h>


// Variable declaration:

extern int a, b;

extern int c;

extern float f;

void main ()


// Variable definition:

int a, b;

int c;

float f;

// actual initialization

a = 10;

b = 20;

c = a + b;

cout << c << endl ;

f = 70.0/3.0;

cout << f << endl ;


When the above code is compiled and executed, it produces the following result:


Comments are closed.