What is the purpose of const qualifier if I can modify it through a pointer in C? [duplicate]

北城余情 提交于 2019-11-28 04:01:58

问题


Possible Duplicate:
Does the evil cast get trumped by the evil compiler?

Hello,

If I can modify a constant through a pointer, then what is the purpose of it? Below is code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
 const int a = 10;
 int *p = (int *)&a;

 printf("Before: %d \n", a);
 *p = 2;
 /*a = 2; gives error*/

 printf("After: %d \n", *p);

 return 0;
}

OUTPUT:

Before: 10
After: 2
Press any key to continue . . .

Using Visual Studio 2008.


回答1:


The reason you could modify the value is because you did a pointer typecast that stripped off the constness:

int *p = (int *)&a;

This typecasts a const int* (namely &a) to an int *, allowing you to freely modify the variable. Normally the compiler would warn you about this, but the explicit typecast suppressed the warning.

The main rationale behind const at all is to prevent you from accidentally modifying something that you promised not to. It's not sacrosanct, as you've seen, and you can cast away constness with impunity, much in the same way that you can do other unsafe things like converting pointers to integers or vice-versa. The idea is that you should try your best not to mess with const, and the compiler will warn you if you do. Of course, adding in a cast tells the compiler "I know what I'm doing," and so in your case the above doesn't generate any sort of warnings.




回答2:


If i can modify a constant through a pointer then what is the purpose of it? below is code:

This is Undefined Behavior and should be avoided at all costs:

§ C99 6.7.3p5

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.



来源:https://stackoverflow.com/questions/4841419/what-is-the-purpose-of-const-qualifier-if-i-can-modify-it-through-a-pointer-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!