Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

it with a const int*?

const
0
Posted

it with a const int*?

0

Because “const int* p” means “p promises not to change the *p,” not “*p promises not to change.” Causing a const int* to point to an int doesn’t const-ify the int. The int can’t be changed via the const int*, but if someone else has an int* (note: no const) that points to (“aliases”) the same int, then that int* can be used to change the int. For example: void f(const int* p1, int* p2) { int i = *p1; // Get the (original) value of *p1 *p2 = 7; // If p1 == p2, this will also change *p1 int j = *p1; // Get the (possibly new) value of *p1 if (i != j) { cout << "*p1 changed, but it didn't change via pointer p1!\n"; assert(p1 == p2); // This is the only way *p1 could be different } } int main() { int x; f(&x, &x); // This is perfectly legal (and even moral!) } Note that main() and f(const int*,int*) could be in different compilation units that are compiled on different days of the week. In that case there is no way the compiler can possibly detect the aliasing at compile time. Therefore the

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.