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