“Change is the only constant in life. Ones ability to adapt to those changes will determine your success in life” Benjamin Franklin
In programming, there are many cases that we have one or more variable and we’re pretty much sure that after initialization of the variable, the content will not change as long as the program is running.
In such case, to make sure a function does not unintentionally change the content of that variable, we can use the keyword const one the left or right side of the data-type of the target variable, and that will turn the variable into read-only variable.
This means we should initialize the target variable right where it is declared and any attempt to reassign a value, will result in compiler error.
This is the structure of a constant variable:
Data-type const variable-name = assigned-value;
const data-type variable-name = assigned-value;
The keyword const can be one the right or left side of the data-type.
Example:
#include <iostream>
using namespace std;
int main() {
int const first = 200;
const int second = 400;
return 0;
}
Remember: we need to initialize the target constant variable right where it is being declared. Any attempt to reassign a constant-variable, will result compile-time error.