Constants

Some values should never change while a program runs, like the number of minutes in an hour or the value of PI. For these, put the word const in front of the declaration. The variable becomes a constant:

#include <iostream>
using namespace std;

int main() {
    const int minutesPerHour = 60;
    int hours = 3;
    cout << hours * minutesPerHour << "\n";
    return 0;
}

Output:

180

* means multiply, so the program prints 3 times 60. You use a constant just like a normal variable.

The compiler protects a constant

If any line tries to change a constant, the program does not compile:

#include <iostream>
using namespace std;

int main() {
    const int maxPlayers = 4;
    maxPlayers = 5;
    cout << maxPlayers << "\n";
    return 0;
}

Output:

main.cpp: In function ‘int main()’:
main.cpp:6:16: error: assignment of read-only variable ‘maxPlayers’
    6 |     maxPlayers = 5;
      |     ~~~~~~~~~~~^~~

The error points to line 6, where the code tries to give maxPlayers a new value. "Read-only" means the value can be read but not changed.

Since you can never assign a new value to a constant, you must give it its value on the same line where you declare it. const int maxPlayers; with no value is also an error.

Why use constants?

A constant gives a number a name. Compare these two lines:

cout << hours * 60 << "\n";
cout << hours * minutesPerHour << "\n";

In the first line, a reader has to guess what 60 means. It could be minutes, seconds, or a pass mark. In the second line, the name tells you. A number with no name in the middle of the code is called a magic number, and it makes code hard to read and easy to break.

Constants use the same camelCase names as other variables. A few well-known constants, like PI, are often written in capital letters.

A constant also stops mistakes. If a line deep in a long program tries to change a value that must stay the same, the compiler tells you before the program even runs.

So when you write a value that you know will never change, make it a const.

In the exercise, make PI a constant and use it to compute the area of a circle.