C++ Pointers and Const
You have learnt to use const keyword for declaring symbolic constants. Using the same keyword, you can also declare constant pointers or constants.
A constant pointer means that the pointer in consideration will always point to the same address. Its address (to which it is pointing to) cannot be modified.
A pointer to a constant refers to a pointer which is pointing to a symbolic constant. Using a pointer to a constant, the constant value (to which this pointer is pointing to) can not be modified, however, the pointer can be made to point to another location. Following examples will make it more clear.
In the following lines, we shall declare four variables :
- a pointer caller ptr
- a constant pointer called cptr
- a pointer named ptrC, pointing to constant
- a constant pointer cprC, pointing to a constant
|int n = 44 ;||// an int|
|int ∗ptr = &n ;||// a pointer to an int|
|++ (∗ptr) ;||// ok : increments int ∗ptr|
|int ∗const cptr = &n ;||// a const pointer to an int|
|++ (∗cptr) ;||// ok : increments int ∗cptr i.e., the contents|
|++cptr ;||// illegal : pointer cptr is const because address can't be modified|
|const int kn = 88 ;||// a const int|
|const int ∗ptrC = &kn ;||// a pointer to a const int|
|++ (∗ptrC) ;||// illegal : int ∗ ptrC is const ie., the contents can't be modified|
|++ ptrC ;||// ok : increments pointer ptrC|
|const int ∗const cptrC = &k ;||// a const pointer to a const int|
|++ (∗cptrC) ;||// illegal : int ∗cptrC is const|
|++cptrC ;||// illegal : pointer cptrC is const|
« Previous Tutorial Next Tutorial »