+ 1
Why is not there any error?
I defined a Constant pointer to constant Data. int x = 5; int y; const int * const ptrX = &x ; *ptrX = 8; // I expected a error and it was accoured. ptrX = &y; // I expected a error and it was accoured. x = 7; // I expected a error buy it was OK!!! *ptrX is point to x variable and i think it's as alias for x. So why you can change x, while *ptrX is const value????
1 Antwort
+ 8
The reason why there is no error is that ptrX is a constant pointer to a constant variable, but x is a normal variable.
A constant pointer to a constant variable cannot change the address it is assigned with, nor can it alter the data at the specified address.
But this does not convert the variable x to a constant. x still remains a normal variable, and can modify the data at the address it is allocated at.