Concept of Constant Pointers in C++

Hello Learners!

In this session, we will learn about some pointer variants. It is called Constant Pointers.
C++ adds the concepts of constant pointer and pointer to a constant. Mostly, these two are not used but are very conceptual topics that give more clarity and space for pointers to use if required. Let us get our hands on it.

Constant Pointers in C++

If one has a value in his/her program and it should not change throughout the program, or if one has a pointer and he/she doesn’t want it to be pointed to a different value, he/she should make it a constant with the const keyword. In simple words, a constant pointer is a pointer that cannot change the address it’s holding. In other words, we can say that once a constant pointer points to a variable then it cannot point to any other variable. Although, we can change the value stored in it provided the address of the variable should not change. For example:
If we have initialized a constant pointer named i, then we could use it to point at a particular address which will be fixed throughout the program. It will be initialized in the following manner:

int a=10;
int * const i= &a;  //Syntax of Constant Pointer
cout<<*i;

Here, a is the variable and i is the constant pointer which is pointing at the address of a. In the output screen, we will see the value 10. We can change the value stored in a and still pointer i will point the address a. This will be implemented something like this:

*i=99;
cout<<*i;

Now, pointer i points to the same address but that address is having a value that is now converted from 10 to 99 and that’s what the output screen will show.

Let’s sum it up together and make it a full program for better understanding and good clarity.

#include<iostream>
using namespace std;
int main()
{
  int a=10;
  int * const i= &a;
  cout<<"1st pointed value: "<<*i;
  *i=99;              // value is getting changed of same address as before
  cout<<"\nModified value: "<<*i;
  return 0;
}

Now, let us see the Output Screen:

1st pointed value: 10
Modified value: 99

The point to be taken care of is that if we ever try to change its address then it will definitely show an error. Let’s take an example :

int a=10,b=44;
int * const i=&a;
i=&b;         //error
cout<<*i;

This program has some serious issue and that is we are using the same pointer i to point to another address which is the address of variable b. That’s definitely not possible in the case of a constant pointer. Therefore, it will show a compilation error.

 

Leave a Reply

Your email address will not be published.