In our daily life, there are some values that never change. For example:
- The number of days in a week is always 7.
- The speed of light in a vacuum is constant.
- A student’s roll number assigned once in a class does not change.
These values remain fixed regardless of circumstances. Similarly, in C++, if we want to create a variable whose value should not be altered during the program execution, we declare it as constant using the const
keyword. The detailed tutorial can be visited here.
A constant in C++ is a variable whose value cannot be modified after initialization.
Why Do We Need Constants?
Contents
Constants are essential because they represent fixed values and prevent accidental modifications.
- Data Safety: Ensures values do not change mistakenly during program execution.
- Readability: Makes the code clearer by indicating that a value is fixed.
- Maintainability: If a constant changes in the future (e.g., tax rate), we only update it in one place.
- Reliability: Prevents bugs that may occur due to unintended modification of important values.
Declaring Constants
In C++, constants can be declared using the const
keyword.
const int daysInWeek = 7;
const float PI = 3.14159;
Once declared, their values cannot be changed.
Example 1: Basic Constant Usage
#include <iostream>
using namespace std;
int main() {
const float PI = 3.14159; // Constant declaration
float radius = 5;
float area = PI * radius * radius;
cout << "Area of circle = " << area << endl;
// PI = 3.14; // ❌ Error: cannot modify a const variable
return 0;
}
Output:
Area of circle = 78.5397
Here, PI
remains fixed throughout the program.
Constants in Classes
We can also use constants inside classes. They are useful for defining values that are common for all objects but should not change, like maximum marks or fixed tax rates.
#include <iostream>
using namespace std;
class Student {
public:
const int rollNumber; // constant data member
Student(int r) {
rollNumber = r;// Initialization using constructor
}
void show() {
cout << "Roll Number: " << rollNumber << endl;
}
};
int main() {
Student s1(101);
Student s2(102);
s1.show();
s2.show();
return 0;
}
Output:
Roll Number: 101
Roll Number: 102
Here, rollNumber
is constant—once assigned through the constructor, it cannot change.
Const Member Functions
A member function can also be declared as const
.
This means it cannot modify any member variables of the class.
class Demo {
int value;
public:
Demo(int v) {
value = v;
}
int getValue() const { // const function
return value;
}
};
If you try to change value
inside getValue()
, the compiler will give an error.
Pointers and Constants
Constants can also be used with pointers in three different ways. To make it simple, think of a pointer as an arrow that shows the address of a variable, while const controls whether the arrow itself can move or whether the value it points to can change.
- Pointer to Constant Data
Here the data is fixed, but the pointer can point somewhere else.
Daily life example: You have a book that you can only read but not edit. However, you can put down this book and pick up another.const int x = 10; const int* ptr = &x; // data is constant, pointer can change
- Constant Pointer
Here the pointer cannot move to another address, but the data at that location can still change.
Daily life example: Imagine you are tied to a single chair. You cannot move to another chair, but you can still adjust the cushion on your chair.int y = 20; int* const ptr2 = &y; // pointer is constant, data can change
- Constant Pointer to Constant Data
Here both the pointer and the data are fixed.
Daily life example: You are tied to a chair, and the cushion on that chair is also locked—you can neither move to another chair nor adjust the cushion.const int z = 30; const int* const ptr3 = &z; // both pointer and data are constant
Daily Life Example
Think of days in a week.
No matter where you live, you always have 7 days in a week.
This is just like a constant variable: it is defined once and never changes.
Or consider a roll number in a classroom—assigned once and fixed for the student.
That’s how constants work in C++.
Comparison: Normal vs Constant vs Static Members
Aspect | Normal Variable | Constant Variable | Static Variable |
---|---|---|---|
Value | Can change anytime | Fixed, cannot be modified | Shared among all objects |
Initialization | Can be later | Must be at declaration/constructor | Declared once, defined outside class |
Usage | For dynamic values | For fixed values | For shared/persistent values |
Safety | Risk of accidental changes | Protected against changes | Prevents duplication, ensures persistence |
Constants ensure stability and prevent accidental modification.
Practice Exercises
- Write a program that uses a constant
PI
to calculate the area of a circle. - Create a class with a constant roll number that is initialized via constructor.
- Write a program to demonstrate a constant pointer to constant data.
- Make a constant member function that returns the value of a private variable.