Alias Optimization (const qualified)

Const-qualified objects can not be modified, and therefore can not be an alias for an lvalue that is used to explicitly modify an object through assignment.

Example:

In the code fragment below, the address of the object pointed to by p is not known, but q points to a const array, and its members can not be modified. Since p is used to modify an object through assignment, p can not be an alias for q.

const int const_array[];

void f (int *p, int i)
{
  int x, y;
  const int *q = &const_array[i];
  x = *q;
  *p = 5;
  y = *q;
  g (x, y);
}
  

Since p is not an alias for q, the second reference to the object pointed to by q can be eliminated, as shown below.

const int const_array[];

void f (int *p, int i)
{
  int x, y;
  const int *q = &const_array[i];
  x = *q;
  *p = 5;
  g (x, x);
}
  

Notes:

The optimization above is allowed because it is known that q points to a const object. Note that it is not sufficient that q have type pointer to const. In other words, the ANSI C standard permits a pointer of type pointer to const to point to a non-const object, in which case this optimization could not be performed without more information.

Although supported by a few compilers, this optimization is not very common.