20D. Const Pointers

Declaring an integer constant size  by

  const int size = 50;
makes it clear that you cannot change the value of size. But it is less obvious what a constant pointer means. In
  int x = 25;
  const int* p = &x;
it is not immediately clear whether the const designator indicates that you cannot change p or that you cannot change *p or both.

The meaning of a const pointer

In C++, declaration
  const int* p = &x;
says that the program cannot use variable p to change *p. In the following, the first three lines are allowed but the fourth is not because it tries to change *p.
  const int x = 25, y = 100;
  const int* p = &x;
  p = &y;
  *p = 3;


A const pointer can point to a nonconst variable

There is nothing wrong with creating a const pointer that points to a non-const variable. For example,

  int x = 25;
  const int* p = &x;
  x = 3;
is fine. Variable x itself is not constant, and you are free to change it. But if you refer to x through p then you cannot change it. It is all about how you refer to a variable.


You cannot copy a const pointer into a nonconst pointer variable

C++ code

  int* p = ...;
  const int* q = p;
is allowed. It copies the pointer from p, where it has no restrictions, into q, where it has a const restriction. It is okay to add restrictions. But you cannot remove a restriction. C++ code
  const int* p = ...;
  int* q = p;
  *q = 0;
tries to change *p by storing the pointer that is in p into another variable that does not have a const restriction. That is not allowed.


Copying a const pointer into another pointer variable

Suppose you want to use a pointer variable as a control variable in a loop. A first attempt might look something like this, where irrelevant details have been replaced by dots.

  void loop(const int* ptr)
  {
    int* p = ptr;
    while(...)
    {
      ...
      p = ...
    }
  }
But that is not allowed because it copies the value of const pointer ptr  into nonconst variable p. That is easy to fix: make p const.
  void loop(const int* ptr)
  {
    const int* p = ptr;
    while(...)
    {
      ...
      p = ...
    }
  }