Const Correctness in C++
(Page 1 of 4 )
One of the biggest advantages of programming in C++ is that you can do the same thing in a variety of ways. At least in theory the compiler lets you do this. Under these circumstances, the difference between a good programmer and a very good programmer lies in the methods they use to accomplish specific tasks. Coding with const correctness in mind is one of the recommended techniques that raises you to the level of a very good programmer. It’s that important to grasp this concept.
It may seem to be just another pain in the neck at first glance. You could say "oh yes; it's not enough that my boss just hit me with lots of coding standards, now I got another issue to watch out for." If you don't know what coding standards are and how they can help you, please read this article. It sums up briefly the idea behind them.
But let's get back to const correctness. Good and excellent programmers use it not because it's trendy; it's because it helps cut the debugging time of code to a minimum and brings issues closer to the compiler. Generally, in coding, it is recommended that you bring any mistakes or errors closer to the compiler. This way the compiler tells you instantly if something is wrong and you evade hours of debugging. For example, you might write in an "if" statement first the constant and only after it the variable:
if (1 == alfa) // instead of alfa == 1
This way, if you for some reason (maybe a bad day or a stressful boss) put only one equal sign, the compiler will warn you at compile time, and you can correct it right away without wasting countless minutes searching for the problem that makes the function/program work, but not the way you were expecting it to. Const correctness can be perceived as a tool or trick in that sense.
If you are interested in investing the time to read more about const correctness, I welcome you aboard. There are few if any prerequisite skills needed for understanding this technique or this article; maybe some basic C++ familiarity, and an understanding of the object oriented programming method as well.
Next: Constant Variables >>
More C++ Articles
More By Gabor Bernat