Programming & Scripting Tutorials

C++: Const(ants)





A constant value is one which cannot change after being set. In C++ - constant variables (or just constant since they really aren't variable) are achieved using the 'const' keyword.
The 'const' system is one of the messy features of C++.
The simplest use is to declare a named constant, obviously you have to initialize it at declaration as it is a constant.
You make a constant (which means it cannot be changed after it's been set) by adding 'const' before a normal variable declaration (and optionally the initialisation).
For example:

const int ConstantOne=66;


The above would create a constant integer that equals 66.

It also works with pointers but you have to be careful where ‘const’ goes to determine whether the pointer is constant, or what it points to is constant, or both.
For example:

const int * ConstantOne


The above declares that ConstantOne is variable pointer to a constant integer.
However the following declares a constant pointer to a variable integer:

int * const ConstantOne


And the following declares a constant pointer to a constant integer.
Basically ‘const’ applies to whatever is on its immediate left (but if there is nothing there it looks on its right), because of this you can also declare a constant integer like this:

int const ConstantOne=66;


The constant pointer to a variable is useful for storage that can be changed in value without the pointer changing what it points to.


You can also create const functions like so:

#include <iostream>

using namespace std;

const char Function1(char input){
return input;
}

int main(){
cout << Function1('a') << endl;
system("PAUSE");
return 0;
}



You can also pass const parameters (this is where it gets messy).
For example a function like this:

void Function1(int input)
{
 cout << input+1 << endl;
}

Lets just say someone passed a const variable into this in that main function.
What would happen is it would still output 15. This shouldn’t technically make sense as we are passing a constant value and then changing it, however in the case of C++ the function creates the variable input and converts the const int to a normal int, therefore the variable 'input' is simple a copy.
Although some people argue this is absolutely fine as it is, it really isn't as we have certainly said int (which is why C++ converts to a normal int) but we haven’t specified what type of integer, therefore it should stay constant (in technical terms), but it doesn’t.


This C++ tutorial was written by


Back to C++

Advertisement: