C++ Constants
Sometimes you have a value that should never change while the program runs, like the number of days in a week or the value of pi. C++ lets you protect such values with the const keyword, turning a variable into a read-only constant.
The const Keyword
Add const in front of a variable declaration to lock its value. Once set, any attempt to change it later causes a compiler error, which is exactly what you want when a value must stay fixed.
Declaring a constant
#include <iostream>
using namespace std;
int main() {
const double PI = 3.14159;
cout << "Pi is " << PI << endl;
cout << "Circle area (r=2): " << PI * 2 * 2;
return 0;
}Note: A const variable must be given a value at the moment it is declared. Writing const int MAX; on its own is an error because there is no way to set it afterward.
Why Use Constants?
- They prevent accidental changes to values that should stay the same.
- They make your intent clear to anyone reading the code.
- They let you name magic numbers, so 7 becomes DAYS_IN_WEEK.
- They can help the compiler optimize your program.
Constants stop accidental changes
#include <iostream>
using namespace std;
int main() {
const int SPEED_LIMIT = 60;
cout << "Limit: " << SPEED_LIMIT << " km/h";
// SPEED_LIMIT = 80; // error: cannot change a const
return 0;
}A common convention is to write constant names in uppercase letters, such as PI or SPEED_LIMIT. This is not required by the language, but it helps readers instantly recognize a value that will not change.