Because sometimes you don't want something to be modified. You want the security of knowing the value can't change. You can then use them as substitutes for hard-coded values that appear in multiple places.
Consider this. You have an array:
And you need to loop through it a few hundred times in your code.
1 2 3 4
|
for (i=0; i < 10; i++)
{
my_array[i] = some_value;
}
|
But then someone comes along and says "Shefon84, those arrays....we actually need them to have a size of 12, not 10". So you have to change the array:
Then you'd have to go through every loop that has anything to do with that array and change the 10 to a 12.
Adding constants takes away that pain:
1 2 3 4 5 6 7 8 9
|
const int ARRAY_SIZE = 10; // We have the security of knowing this can't change
int my_array[ARRAY_SIZE];
// later...
for (i = 0; i < ARRAY_SIZE; i++)
{
my_array[i] = some_value;
}
|
"Shefon84, we need that array changing to a size of 12, not 10".
|
const int ARRAY_SIZE = 12;
|
That's now a two minute job and you still have the security of knowing that the value can't change in the code.