Understanding const pointers and variables in C++
In modern C++, we are used to see const pointers. They are a useful way to avoid changes in memory passed to a function. As such, they are very common in function declarations.
The const word, however, has other uses. It turns out that when the const keyword is applied to the pointer itself (instead of the contents of the pointer), the const modifier is also very useful.
When we say, for example, const Type *t, we are saying that the contents of the object pointed by t cannot be changed. However, we can just as well say Type * const t, which means that the pointer t is unchangeable.
For example, check the following code:
int main() { int i, j; const int *p = &i; // *p =0; // ERROR: cannot modify the memory pointed by p p = &j; int * const q = &i; *q = 0; // q = &j; // ERROR: cannot modify the pointer q return 0; int const k = 0; // k = 1; // ERROR: cannot modify the variable k } |
See that Type * const t may be a syntactical clue for how the code is organized, because in short methods we usually don’t want to have variables and pointers changing. Thus, in such a case we should avoid having variables that are not const.
Understanding const Syntax
The reason for the difficulty of understanding the behavior of expressions such as Type * const t is due to the complexity of the C++ syntax.
Notice that the example const int k can also be written as int const k (as shown above). This denotes that the const modifier is intended to the variable.
When we have a pointer, however, we can also have a const memory location, which is represented as Type * const p. The const attribute is now referring to the content of the pointer, and this is indicated by having it after the * operator.
To simplify the notation, a better way to write const attributes is to make this difference explicit as in the examples bellow:
Type const * p; // can't modify what p points to Type * const q; // can't modify q itself Type const * const t;// can't modify neither t or point value |
As a quick tip to remember the correct syntax, always keep the const close to the * operator, to make its meaning easier to understand.
Similar Posts:
About the Author
Carlos Oliveira holds a PhD in Systems Engineering and Optimization from University of Florida. He works as a software engineer, with more than 10 years of experience in developing high performance, commercial and scientific applications in C++, Java, and Objective-C. His most Recent Book is Practical C++ Financial Programming.
Your summary is a little confusing. I assume “same as above” refers to the previous section, and not the above line.
Type const * p; // can’t modify what p points to
Type * const q; // can’t modify q
Type const * const t; // can’t modify either
Codepadded here: codepad.org/avZroxQe
For more const correctness, I’ve always liked the C++ Faq
By David on Dec 4, 2009
Thanks David, I corrected the small confusion on the last listing.
By coliveira on Jan 16, 2010