what is difference between pointer to constant and constant pointer explain it with example? This very specific interview question for a c or c++ programmer.  It is a basic concept and every c/c++ developers must know. Let us discuss one by one.

If something is constant , it means it is not modifiable. const is a qualifier in c programming language. we also know that pointers in c are a variable which points to another variable.

 Pointer to constant

const int *ptr

ptr is a pointer to a const int type. We can modify ptr itself but the object pointed to by ptr shall not be modified. 

constant pointer

int * const ptr;

So here ptr is constant and we cannot modify ptr. we can modify the object which is pointed by ptr.

constant pointer to constant variable

const int * const ptr;

The declaration shows that neither ptr can be modified nor the variable at which it will point. Kindly see below code with example for each case.

#include <iostream>
using namespace std;

int numa = 5;
int numb = 6;

void pointer_to_variable()
	int *p = &numa;
	*p = 7;
	cout << *p << endl;
	p = &numb;
	cout << *p << endl;

void pointer_to_const_variable()
	const int *p = &numa;
	p = &numb;
   // *p = 7; // error

void const_pointer_to_variable()
	int *const p = &numa;
	*p = 7; // no issue
	// p = &numa; // error

void const_pointer_to_const_variable()
	const int * const p = &numa;
	//*p = 8; // error
	 //p =&numb; // error

int main()
	return 0;



Related Contents to follow