Who`s Afraid to Be Const Correct? Reading Const Correctly in C++
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.
Who`s Afraid to Be Const Correct? Reading Const Correctly in C++ - Const Declarations (Page 2 of 6 )
The const keyword can be used inside classes for static/non static data members and function members (and their respective arguments). Outside classes it can be used for global or namespace constants, function arguments and for static variables (these are variables that are for the private use of the functions in their respective source files, and are not meant to be accessed by anything else [K&R]). For pointers and references you can specify whether the pointer or reference itself is const, the data pointed to or referenced is const… or both.
Constants may also help you to get rid of ‘magic values’ in your code. This means that instead of ‘char msg;’ you can write more readable declarations like ‘char msg[MAX_MSG_LEN];’. The first declaration uses a ‘magic value’ because it is not immediately clear what 128 stands for (it just magically appears). On the other hand ‘MAX_MSG_LEN’ can be read and understood to represent the maximum message length.
An additional benefit of using constants is that you can group them together at the beginning of your source code and reuse them whenever possible (‘MAX_MSG_LEN’ can easily be used to declare an array more than once in your code!).
Please don’t declare MAX_MSG_LEN this way:
#define MAX_MSG_LEN 128
It works (the preprocessor replaces MAX_MSG_LEN with 128 before your code is seen by the compiler) but #defines are very hard (and clumsy) to debug… and they are not typesafe!