Thursday, August 15, 2019

C++ Interview Questions 2: const pointer vs pointer to a const

Q: What are the differences of const int *ptrint  *const ptr, const int const *ptr, and int const *ptr?

The key is to read them from right to left.

For the key word, const, please refer to this note.

Thus,

int * is a regular pointer to a regular integer;

const int * ptr is a regular pointer, *ptr, pointing to a constant integer;

int  *const ptr is a constant pointer, *ptr, pointing to a regular integer;

const int const *ptr is a constant pointer, *ptr, pointing to a constant integer;

int const *ptr == const int *ptr, since here int and const can be exchanged.

Let us look at some examples:

const int val = 5;
const int *ptr = &val;
*ptr = 10; // is wrong, since the object pointed is a constant integer
ptr++; //is ok, since the pointer is a regular pointer, 
       //now ptr points to a different address, but it still                 
       //cannot change the value of the object it is pointing to;


const int val = 5;
int * const ptr = &val;
*ptr = 10; //  is ok, since the object pointed is a regular integer
ptr++; //is wrong, since the pointer is a constant pointer, 
       //and can only point to fixed address.


const int val = 5;
const int * const ptr = &val;
*ptr = 10; //  is wrong, since the object pointed is a constant integer
ptr++; //is wrong, since the pointer is a constant pointer

No comments:

Post a Comment