如果我可以通过 C 中的指针修改 const 限定符,那么它的用途是什么?
可能的重复:
邪恶的编译器会打败邪恶的演员吗?
你好,
如果我可以通过指针修改一个常量,那么它的目的是什么? 下面是代码:
#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;
}
输出:
之前:10
之后:2
按任意键继续。 。 。
使用 Visual Studio 2008。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以修改该值的原因是因为您进行了指针类型转换,剥离了 const 性:
此类型转换为 const int*(即
&a< /code>) 转换为
int *
,允许您自由修改变量。通常编译器会警告您这一点,但显式类型转换抑制了警告。const
背后的主要原理是为了防止您意外修改您承诺不会修改的内容。正如您所看到的,它不是神圣不可侵犯的,您可以不受惩罚地抛弃常量性,就像您可以做其他不安全的事情一样,例如将指针转换为整数,反之亦然。这个想法是你应该尽量不要搞乱const
,如果你这样做,编译器会警告你。当然,添加强制转换会告诉编译器“我知道我在做什么”,因此在您的情况下,上述内容不会生成任何类型的警告。The reason you could modify the value is because you did a pointer typecast that stripped off the
const
ness:This typecasts a
const int*
(namely&a
) to anint *
, 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 awayconst
ness 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 withconst
, 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.这是未定义的行为,应该不惜一切代价避免:
This is Undefined Behavior and should be avoided at all costs: