Search code examples
cpointersconstants

Constant pointer vs Pointer to constant


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.


Solution

  • 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