const pointer

I'm trying to get a grasp on const pointer. Given the following code:

1
2
  const int num1{100};
  const int* const p_num1 {&num1};


In the second line, does const int mean that num1 can't be changed by p_num1, and const p_num1 means that p_num1 can't be redirected to point to another variable?
Last edited on
L1 - the value of num1 can't be changed
L2 - the value of p_num1 can't be changed and the memory contents pointed to by p_num1 also can't be changed

if you have:

1
2
const int* pnum2 {&num1};
int* const pnum3 {&num1};


then:
L1 - pnum2 is a pointer to memory whose contents can't be changed but the value of pnum2 can be
L2 - pnum3 is a pointer to memory whose contents can be changed but the value of pnum3 can't

Note that const int* and int const* are the same.

For definitions like these, it's useful if you read them right to left:
L1 - pnum2 is a pointer to const int
L2 - pnum3 is a const pointer to int

so for:
 
const int* const p_num1 {&num1};


p_num1 is a const pointer to const int
Last edited on
Thanks, seeplus.
Nicely explained. I appreciate your time, seeplus. Thanks again.
Topic archived. No new replies allowed.