Consider the following 2 programs prog1 and prog2.Here if I try to change the value of the const
qualified variable i
Why are we allowed to change the value of a read-only
const
qualified variable in any circumstance?
We aren't. I don't see why you assume that, nor which example shows that.
why the discrimination between changing the value of a read-only const qualified variable using a pointer (which is allowed,with a warning)
Again: it's not allowed, hence the warning. (Warnings are to be taken seriously - you don't seem to give any significance to them...) It's just that the compiler doesn't know that the pointer points to some const
-qualified object (because it's declared as non-const T *
).
As to why changing the variable works:
Explanation #1: it's undefined behavior (a constraint violation), so it can do anything.
Explanation #2: probably it's just stored on the stack like local automatic variables, and you can indeed change it.