Why are we allowed to change values of “const” qualified variables?Why pointers are allowed for this,but not assignment?

后端 未结 2 927
耶瑟儿~
耶瑟儿~ 2021-01-13 14:15

Consider the following 2 programs prog1 and prog2.Here if I try to change the value of the const qualified variable i

2条回答
  •  难免孤独
    2021-01-13 14:38

    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.

提交回复
热议问题