In C++, constants are values that remain unchangeable throughout the program. If a value should stay the same such as fixed rates or system limits—it should be declared as a constant using the const
keyword.
Declaring a Constant Variable
To prevent a variable’s value from being modified, use const
before the type:
Example
C++
x
using namespace std;
int main() {
const int maxSpeed = 300; // Declaring a constant variable
// Attempting to modify the constant value
maxSpeed = 200; // This line will cause a compilation error
cout << "Max Speed: " << maxSpeed << " km/h" << endl;
return 0;
}
Explanation:
maxSpeed
is set as a constant, meaning it cannot be changed later.- Trying to assign a new value causes an error.
When to Use Constants
If a value should never change, always declare it as a constant to avoid accidental modifications.
Example
C++
const int hoursPerDay = 24;
This ensures the value always remains 24 throughout the program.
Important Notes About Constants
- A constant must be assigned a value at declaration:
C++
const int rpmLimit = 8000;
- This will not work (causes an error):
C++
const int rpmLimit; // No value assigned rpmLimit = 8000;
rpmLimit = 8000; // error: cannot assign to a constant