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

27th Mar 2019, 2:25 PM
Alireza Abbasi
Alireza Abbasi - avatar
1 Resposta
+ 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.
27th Mar 2019, 3:17 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar