2.1 Non-class use of const

Let us first example some uses of const in the context of C.

const int x = 23;
// ...
x = x + 1;

This code generates a compile-time error because x is marked const, which means that its value should not change. The assignment operation x = x + 1 violates the rule that a const variable cannot be changed. As a result, the compiler issues an error.

void f(const char *p)
{
  *p = '\0';
}

The above code also generates an error message. This time, the parameter p is ``a pointer to const char'', which means what p points to should never change. The assignment operation attempts to change what p points to, hence the error message.

Note that the following code does not generate any error:

void f(char const *p)
{
  *p = '\0';
}

In this case, p is ``a const pointer to a char'', which means the pointer itself cannot change, but the character that it points to can be altered. Let us examine one last case:

const char *f(const char *p)
{
  while (*(p++) != '\n');
  return p;
}

This code does not generate any errors, either. This is because p is, again, a ``pointer to const char''. The subroutine never once changes what p points to. The code changes the pointer to point to another location, but not the value at the location.

It is possible to write the following subroutine:

int f(const char const *p)
{
  return *p == '\0';
}

In this case, p is a ``const pointer to const char'', which means the pointer itself cannot change, and what it points to cannot change, either.

Copyright © 2006-09-19 by Tak Auyeung