(from 2 simple variable initialization question)
A really good rule of thumb regarding const
:
Read Declarations Right-to-Left.
(see Vandevoorde/Josutiss "C++ Templates: The Complete Guide")
E.g.:
int const x; // x is a constant int
const int x; // x is an int which is const
// easy. the rule becomes really useful in the following:
int const * const p; // p is const-pointer to const-int
int const &p; // p is a reference to const-int
int * const * p; // p is a pointer to const-pointer to int.
Ever since I follow this rule-of-thumb, I never misinterpreted such declarations again.
(: sisab retcarahc-rep a no ton ,sisab nekot-rep a no tfel-ot-thgir naem I hguohT :tidE
Equally, you can write your function signatures to this rule:
void foo (int const * const p)
now, p
is a const-pointer to const-int. This means that inside the function's body, you cannot let p
point to something else, i.e. you can not change the pointer, nor can you change what it is point to.
p being a const-pointer is information that is really only relevant to your function's body, and you should omit this information from the header file:
// foo.h
void foo (int const *p);
then
// foo.cc
void foo (int const * const p) {
// Here, the const serves you as the implementor as an additional
// safety gear.
}