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.

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:

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.

Published on November 21st, 2009

2 Responses to “Understanding const pointers and variables in C++”

Your summary is a little confusing. I assume “same as above” refers to the previous section, and not the above line.