A variable is an entity whose value can vary in a program. But sometimes, we need to fix the value of a variable for some purpose.

For example, to calculate the area of a circle, we can store the value of PI which  is 3.14 in a variable. However we need to make sure that this value is not altered in the program otherwise we may get wrong results.

So to fix the value of a variable, we use the keyword const before its data type.

Here are few examples :

  1. const int num = 3 ; 
  2. const char ch = ‘z’ ;
  3. const float PI = 3.14 ;

After the const keyword is placed before the data type of a variable, any attempt to change its value generates a compile-time error !!

The following program illustrates this point.

//ChewCode program to demonstrate working of const keyword
using namespace std;

int main()
    const int i=3;
    cout << i << endl;
    i = i + 10 ;  //This is an attempt to alter value of a constant variable i
    cout << i;
    return 0;

This program won’t execute as here we are trying to alter the value of variable ‘i’ in statement 12. This ‘i’ has been declared using const keyword in line 8.

Here is a live preview of the program. Notice the compiler generated error at the end of the screen.

variable using const keyword in C++

The const keyword can also be used with other entities in C++. But we will deal with them later on.

Hope you are clear with the concept of const keyword. Let us know your queries in comments below.


Founder & Senior Editor of ChewCode.com and Editor at GizmoBolt.com. Sakshi is currently pursuing MCA. She is a foodie and has a unique love for learning computer programming languages. Follow her on Google + | Facebook | Twitter. Contact her at [email protected] for feedback and sending tips.

Tags: , , , , , , ,

Leave A Response