I find that in the following code snippet
const int i = 2;
const int* ptr1= &i;
int* ptr2 = (int*)ptr1;
*ptr2 =3;
i
's value changes to 3. What I could like to know is why is this allowed. What are the situations in which this could become helpful?
In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization.
Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).
You can't. The const keyword is used to create a read only variable. Once initialised, the value of the variable cannot be changed but can be used just like any other variable.
Because the data type being pointed to is const, the value being pointed to can't be changed. We can also make a pointer itself constant. A const pointer is a pointer whose address can not be changed after initialization.
It's allowed because you have overruled the constness of ptr1 by casting it to a non-const pointer. This is why casts can be very dangerous.
Note that some compilers, such as GCC, will not allow you to cast away const status like this.
You have broken the constantness guarantee by playing pointer tricks. This is not guaranteed to work all the time and could invoke almost any behavior depending on the system/OS/compiler that you throw it at.
Don't do that.
Or at least don't do that unless you really know what you are doing and even then understand that it is not in the least portable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With