POINTERS AND CONST
Pointers are very interesting aspects of C++ language. If you master this concept, it is useful in all the other topics, specially data structures and algorithms. An interesting part though, is the interaction of pointers with const keyword.
POINTERS
& CONST
We have learnt to use const keyword for declaring symbolic constants. Using the same keyword, we can also declare constant pointers or pointers to 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 constant pointer must be
initialized at time of creation. The address stored in that pointer at time of
creation becomes its final value and it cannot be changed further. But the
value at that location can be modified.
General syntax :
int * const iptr = new int ();
See the use of keyword const and also that it is mandatory to initialize the constant pointer the moment it is created.
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 at some other address.
General syntax :
const int * iptr;
iptr = new int ();
See the use of keyword const. Unlike the previous case,
a pointer to a constant need not be initialized at time of creation.
The following examples will make it clearer.
If you want articles on a particular topic, comment down on
this post.
Do not stop here. Read all articles related to C++ here.
If you want to contribute any article for the website, feel
free to share it on coding.nkcoder@gmail.com. We will
publish it on the website with your name.
Download the pdf form of this article here.
Related Topics :
Static & Dynamic Allocation of memory
Declaration & Initialization of pointers
Post a Comment