C - Pointer to Constants

Introduction

You can use the const keyword when you declare a pointer to indicate that the value pointed to cannot be changed.

long value = 9999L;
const long *pvalue = &value;               // Defines a pointer to a constant

For example, the following statement will now result in an error message from the compiler:
*pvalue = 8888L;  // Error - attempt to change const location

What pvalue points to must not be changed. You can change the value:

value = 7777L;

The pointer itself is not constant, so you can still change what it points to:

long number = 8888L;
pvalue = &number;                 // OK - changing the address in pvalue

This will change the address stored in pvalue to point to number.

You cannot use the pointer to change the value that is stored.

You can change the address stored in the pointer, but using the pointer to change the value pointed to is not allowed.