Programming‎ > ‎C++‎ > ‎Programming Tips‎ > ‎Misc‎ > ‎

Use const whenever possible

Things to Remember
- Declaring something const helps compilers detect usage errors, const can ve applied to objects at any scope, to function parameters and return types, and to member functions as a whole.
- Compilers enforce bitwise constness, but you should program using conceptual constness.
- When const and non-const member functions have essentially identical implementations, code duplication can be avoided by having the non-const version call the const version.
 
The const allows you to specify the semantic constraint that a particular object should not be modified.
char name[] = "Delta";
char *myName = name;                    // non-const pointer, non-const data
const char *myName = name;            // non-const pointer, const data
char const *myName = name;            // non-const pointer, const data
char * const myName = name;           // const pointer,        non-const data
const char * const myName = name;   // const pointer,        const data
 
If the word const apprears to the left of asterisk, what's pointed to is constant; if the word const appears to the right of the asterisk, the pointer itself is constant; if const appears on both sides, both are constant.
Comments