Why would you use constants?

Recently I've learned about constants, but while they seem cool and all I don't see the use. Why use:
const int MONTHS = 12;
whenever it seems that
int months = 12;
Would do the same thing, and you could modify it. I'm sorry if this is a stupid question. Could someone tell me some uses for symbolic constants?
How many years have more than 12 months? I doubt you ever want to change that.

Constants are good because you can't change them by accident. Certain things like the size of an array needs to be a constant.
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:
 
int my_array[10];


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:
 
int my_array[12];


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.
Last edited on
One of the reasons you would use it because you can't modify it and thus you can be sure that it's the same throughout your code.

For instance if you used:

1
2
3
const int months = 12 ;

unsigned days_in[months] ;


later in the code,

1
2
     for ( auto i = 0; i < months ;  ++i )
          std::cout << daysin[i] << '\n' ;


You want months to be the same as when you defined it. If someone could change it, that would be disastrous for your code.

Also, compilers can (often) effectively replace const values of that sort with literals, which they cannot do with non-const variables.
Thanks guys, that clears up a lot of questions about it :)
Topic archived. No new replies allowed.