Why can we increase the dereferenced pointer to constant data in C ++?

I was surprised that C ++ allows you to increase the dereferenced pointer to constant data, which it should not allow through a pointer to const data. Consider the code:

#include<iostream> #include<climits> using namespace std; int main(){ int x = 2; const int *xPtr2 = &x; *xPtr2++; cout << x << endl; } 

But still, the value of x is 2. This means that * xPtr2 did not actually increase. I also tried * xPtr2 = 3, but this time it shows a compilation error. Why is this so?

+5
source share
4 answers

Here, the priority of ++ is greater than that of *. Hence,

 *xPtr2++ 

equivalently

 *(xPtr2++) 

Since xPtr2 is not a pointer to a constant, but a pointer to constant data, then incrementing xPtr2 and dereferencing it are fine in this case (but not others), and therefore a compilation error does not occur.

+5
source

An increment has a higher priority than dereferencing. This way you increment the pointer, and then cast a magnifying pointer. The pointer is not a constant, so it can be increased.

+2
source

The ++ operator takes precedence over dereferencing. Basically you are looking for a pointer that has been enlarged.

For the behavior you are trying to execute, you must wrap the pointer in parens.

 (*xPtr2)++; 

The same goes for assignment - you are trying to assign int to int * . He will work with partners.

 (*xPtr2) = 3; 

See your example in ideone .

+2
source

You mentioned

dereference pointer to constant data

So, consider the following code

 #include <stdio.h> int main() { const int foo = 0xdead; int* bar = (int*) &foo; *bar = 0xcafe; printf("const int foo = %#x", foo); return 0; } 

Output: const int foo = 0xcafe

In C, C ++ const is just a time compiler for variables. This means that the compiler does not want to change the value of const at compile time. At run time, there is no concept of const => all local variables are stored on the stack, all static and global variables are stored in the .data section. This way you can dereference a constant and change it only at runtime

0
source

All Articles