vengets vengets - 1 year ago 80
C Question

Constant pointer vs Pointer to constant

I want to know the difference & how it works.

const int* ptr;


int * const ptr;

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

Answer Source
const int* ptr; 

declares ptr a pointer to const int type. You can modify ptr itself but you can't modify the object pointed to by ptr.

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


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.

int a = 10;
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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download