Constant Pointers - C Pointer

C examples for Pointer:Constant Pointer

Introduction

To ensure that the address stored in a pointer cannot be changed, use the const keyword in the declaration of the pointer.

Here's how you could ensure that a pointer always points to the same thing:

int count = 43;
int *const pcount = &count;       // Defines a constant pointer

The second statement declares and initializes pcount and indicates that the address stored must not be changed.

The following statements will result in an error message when you compile:

int item = 34;
pcount = &item;                   // Error - attempt to change a constant pointer

You can still change the value that pcount points to using pcount though:

*pcount = 345;                    // OK - changes the value of count

You can create a constant pointer that points to a value that is also constant:

int item = 25;
const int *const pitem = &item;

The pitem is a constant pointer to a constant so everything is fixed.

To make everything fixed and inviolable, you could specify item as const.


Related Tutorials