-1

As we know in reference, a const can have a reference to either a const or non-const. However I have a question for the following pointer:

#include<iostream> using namespace std; int main() { const double pi = 3.14; const double *cptr = &pi; //we point to a const double (above) double dval = 3.14; cptr = &dval; cout<<*cptr<<endl; } 

What I am not understanding is "const double *cptr" if we read it from right to left we have cptr is a pointer that points to a const double.

However, below we have double dval = 3.14; with cptr = &dval; double dval is not a constant, from what I am understanding we can still point to a non constant correct?

4
  • 1
    The const in const double *cptr simply means "cptr can not change the double it points to". Commented Jul 2, 2022 at 18:12
  • ...or to put it slightly differently, const doesn't really mean "constant" nearly as much as it means "read only". Having a read-only pointer to a writable item just means you can't write to the item via that pointer. Commented Jul 2, 2022 at 18:46
  • "a const can have a reference to either a const or non-const" I hope you don't mean to have a non-const reference to a const variable Commented Jul 2, 2022 at 18:48
  • This is an example straight from the book C++ Primer where it is already explained thoroughly. There the author has explained this line by line in a very beginner friendly manner so the explanation can be looked up there. Commented Jul 2, 2022 at 19:13

2 Answers 2

2

That's perfectly fine.

After the reassignment

cptr = &dval; 

it just means that you can't dereference the pointer cptr to modify what it points to.

In other words, it's not possible to do e.g.

*cptr = 2.72; 
Sign up to request clarification or add additional context in comments.

1 Comment

Ok thank you! I thought because we specifically specified the pointer points to a const double we absolutely have to point to a double that is const. Thanks for clarifying!
1

Similar to having a const & to a non-const object you can have pointers to const pointing to non-const objects.

Suppose you'd use a pointer rather than a reference for pass-by-reference, then this

 void foo(const double* p); 

Means that the function cannot modify the pointee. Whether the passed pointer does actually point to a const double doesn't matter that much to the function, because anyhow it is not modifying it:

double dval = 3.14; foo(&dval); 

After the function call, dval is still 3.14.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.