C++ Constants
A constant is a named value that never changes while a program runs. Constants hold fixed values, such as 60 seconds in a minute.
A constant prints
const marks days as a constant with the value 7. The print line shows its value.
#include <iostream>
int main() {
const int days = 7;
std::cout << days << std::endl;
return 0;
}A constant in arithmetic
The constant holds 60 seconds for one minute. Three minutes hold 3 times 60 seconds, which is 180.
#include <iostream>
int main() {
const int secondsPerMinute = 60;
std::cout << 3 * secondsPerMinute << std::endl;
return 0;
}A constant cannot change
This program tries to assign a new value to a constant. The compiler refuses the program and reports the error line below.
#include <iostream>
int main() {
const int limit = 10;
limit = 20;
std::cout << limit << std::endl;
return 0;
}Example
#include <iostream>
int main() {
const int secondsPerMinute = 60;
std::cout << "2 minutes: " << 2 * secondsPerMinute << " seconds" << std::endl;
std::cout << "5 minutes: " << 5 * secondsPerMinute << " seconds" << std::endl;
return 0;
}Key points
- Use the word const to declare a constant.
- A constant gets its value in the line that declares it.
- A program can read a constant many times.
- Arithmetic means working with numbers in sums and products.
- A constant can take part in arithmetic.
- A line that assigns a new value to a constant fails to compile.
In this example, the constant holds 60 seconds for one minute. The first print line works out two minutes as 120 seconds. The second print line works out five minutes as 300 seconds.
Note
A constant keeps one value for the whole run.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C++ Compiler
Exercise
What happens when a program assigns a new value to a constant?