To prevent modification of variable values by others or yourself, you can employ the const keyword.
This declares the variable as “constant,” rendering it unchangeable and read-only.
const int myNum = 15; // myNum will always be 15 myNum = 10; // error: assignment of read-only variable ‘myNum’ |
It’s advisable to declare a variable as constant when its values are not expected to change.
const int minutesPerHour = 60; const float PI = 3.14; |
Upon declaring a constant variable, it is mandatory to assign it a value.
Like so:
const int minutesPerHour = 60; |
However, this approach will not function:
const int minutesPerHour; minutesPerHour = 60; // error |
Another aspect of constant variables is that it’s considered good practice to declare them using uppercase letters.
While not obligatory, this practice enhances code readability and is commonplace among C programmers.
const int BIRTHYEAR = 1980; |