Show: Object Pascal C++
Display Preferences

Pointer Constants

From Appmethod Topics
Jump to: navigation, search

Go Up to Pointers Index

A pointer or the pointed-at object can be declared with the const modifier. Anything declared as a const cannot be have its value changed. It is also illegal to create a pointer that might violate the nonassignability of a constant object. Consider the following examples:

int i;                       // i is an int
int * pi;                    // pi is a pointer to int (uninitialized)
int * const cp = &i;         // cp is a constant pointer to int
const int ci = 7;            // ci is a constant int
const int * pci;             // pci is a pointer to constant int
const int * const cpc = &ci; // cpc is a constant pointer to a
                             // constant int

The following assignments are legal:

i = ci;                     // Assign const-int to int
*cp = ci;                   // Assign const-int to
                            // object-pointed-at-by-a-const-pointer
++pci;                      // Increment a pointer-to-const
pci = cpc;                  // Assign a const-pointer-to-a-const to a
                            // pointer-to-const

The following assignments are illegal:

ci = 0;                     // NO--cannot assign to a const-int
ci--;                       // NO--cannot change a const-int
*pci = 3;                   // NO--cannot assign to an object
                            // pointed at by pointer-to-const
cp = &ci;                   // NO--cannot assign to a const-pointer,
                            // even if value would be unchanged
cpc++;                      // NO--cannot change const-pointer
pi = pci;                   // NO--if this assignment were allowed,
                            // you would be able to assign to *pci
                            // (a const value) by assigning to *pi.

Similar rules apply to the volatile modifier. Note that const and volatile can both appear as modifiers to the same identifier.

Personal tools
In other languages