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 :
- const int num = 3 ;
- const char ch = ‘z’ ;
- 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;
const int i=3;
cout << i << endl;
i = i + 10 ; //This is an attempt to alter value of a constant variable i
cout << i;
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.
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.