Main Content

What does const mean? C and C++

Archive - Originally posted on "The Horse's Mouth" - 2010-01-15 08:30:28 - Graham Ellis

If you declare a variable to be a const, you're telling the compiler that it's a read-only variable and that it won't be changed throughout its existance. A values that's passed in as a parameter to a function, for example, will be left alone until the function exits. That does not stop you from deriving other values from the variable or using it to make a decision - if you couldn't, there would be no point in passing it in to the function!

Here are two C++ methods taking a float into a function. In teh first case I have commented out the calculation that would change the incoming value as it lead to a compile time error.

void Hotel::setoccu(const float *inval) {
   // inval *= 0.9; // Compiler complain like sh**
   occrate = *inval * 0.9;
   }
 
void Hotel::setoccu(float inval) {
   inval *= 0.9; // Compiler won't complain like sh**
   occrate = inval;
   }


Why use const?
1. Efficiency of code / may run a bit quicker
2. Safety / provides an extra check to help the programmer