Declaration of Constanta (const)

It is simple in concept, variables declared with ‘const’ added become constants and cannot be altered by the program, but, in the way is has to be used to bodge in a substitute for one of the missing features of C++, it gets horridly complicated and frustratingly restrictive. The following attempts to explain how 'const' is used and why it exists.

Const gives you the ability to document your program more clearly and actually enforce that documentation. By enforcing your documentation, the const keyword provides guarantees to your users that allow you to make performance optimizations without the threat of damaging their data. For instance, const references allow you to specify that the data referred to won't be changed; this means that you can use const references as a simple and immediate way of improving performance for any function that currently takes objects by value without having to worry that your function might modify the data. Even if it does, the compiler will prevent the code from compiling and alert you to the problem. On the other hand, if you didn't use const references, you'd have no easy way to ensure that your data wasn't modified.

Such constants are useful for parameters which are used in the program but are do not need to be changed after the program is compiled. It has an advantage for programmers over the C preprocessor ‘#define’ command in that it is understood & used by the compiler itself, not just substituted into the program text by the preprocessor before reaching the main compiler, so error messages are much more helpful.

It also works with pointers but one has to be careful where ‘const’ to determine whether the pointer
or what it points to is constant or both. For example look statement below:
const int myconstant = 10       //An int which can't change value. Similar to #define in C but better.
const int * myconstant            //Variable pointer to a constant integer.
int const * myconstant            //Same as above.
int * const myconstant            //Constant pointer to a variable integer.
int const * const myconstant   //Constant pointer to a constant integer.


Recent Entries