In C++ we can define a variable as a constant. Meaning, its value does not change for the life of the program.
We use const
keyword to define constant.
const int weightGoal = 100;
With this statement we have set the integer weightGoal
to 100. It cannot be changed during the program.
If we want to change the value of weightGoal
, we will have to edit the source code and recompile it.
Look at the error messages that are generated when we attempt to compile and execute the code below. You will see that our attempt to change a constant variable fails.
//Goal: use constant variables
#include <iostream>
using namespace std;
int main()
{
const int weightGoal = 100;
cout<<"WeightGoal = "<<weightGoal<<"\n";
weightGoal = 200;
cout<<"WeightGoal = "<<weightGoal<<"\n";
return 0;
}
//OUTPUT:-
man.cpp: In function ‘int main()’:
man.cpp:8:16: error: assignment of read-only variable ‘weightGoal’
8 | weightGoal = 200;
| ~~~~~~~~~~~^~~~~