Who`s Afraid to Be Const Correct? Reading Const Correctly in C++
(Page 1 of 6 )
You can do more with the const keyword in C++ than you can in C. Many programmers avoid using it, however, in part because it can be a little tricky to understand at first. Jun Nakamura explains how to use the keyword, and the excellent effect it can have on your code.
Introduction
The const keyword has become quite versatile when you compare its abilities in C++ to its abilities in C. Unfortunately I have to say that I see more programmers avoiding it than using it to their benefit. Most often the reason they refuse to use it is simply because they feel it just gets in their way or because they find it impossible to introduce it into a project that has been going for a while. After all const-correctness is something you should implement from the beginning and not introduce as an afterthought.
Still if you spend a little bit of time looking into the effect this keyword has on your code, it can become your greatest friend. This friend may be a bit hard to understand at first though. Just take a look at the following declarations:
constchar *str = “this looks very familiar”;
char const *str = “though this has my preference”;
char * const str = “what is const here?”;
constchar * const str = “now it is getting stranger”;
char const * const str = “and stranger!”;
This awkward placing of const confuses more than it helps, but once you know how to interpret the effect of const correctly, you will dictate which variable/objects should not be modified! Not only are you communicating this to the compiler so that it can help you track possible violations of that constraint, but you are also communicating this to other programmers (including yourself) that try to make good use of your code.
Next: Const Declarations >>
More C++ Articles
More By J. Nakamura