Constant pointer vs Pointer to constant

Venkatesh K picture Venkatesh K · Jan 31, 2014 · Viewed 263.4k times · Source

I want to know the difference between

const int* ptr;

and

int * const ptr; 

and how it works.

It is pretty difficult for me to understand or keep remember this. Please help.

Answer

haccks picture haccks · Jan 31, 2014
const int* ptr; 

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

const int a = 10;
const int* ptr = &a;  
*ptr = 5; // wrong
ptr++;    // right  

While

int * const ptr;  

declares ptr a const pointer to int type. You are not allowed to modify ptr but the object pointed to by ptr can be modified.

int a = 10;
int *const ptr = &a;  
*ptr = 5; // right
ptr++;    // wrong

Generally I would prefer the declaration like this which make it easy to read and understand (read from right to left):

int const  *ptr; // ptr is a pointer to constant int 
int *const ptr;  // ptr is a constant pointer to int