-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?

  • 1
    The `const` in `const double *cptr` simply means "cptr can not change the double it points to". – Drew Dormann Jul 02 '22 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. – Jerry Coffin Jul 02 '22 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 – MatG Jul 02 '22 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](https://www.informit.com/store/c-plus-plus-primer-9780135161777). – Jason Jul 02 '22 at 19:13

2 Answers2

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;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 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! – tall_call_9129 Jul 02 '22 at 18:23
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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185