更改C常量的值 [英] changing const value in C

查看:86
本文介绍了更改C常量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现在以下code段

I find that in the following code snippet

const int i = 2;  
const int* ptr1= &i;  
int* ptr2 = (int*)ptr1;  
*ptr2 =3;

I 的值更改为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?

推荐答案

这是允许的,因为你已经将其转换为一个非const指针否决ptr1的的常量性。这就是为什么强制转换是非常危险的。

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.

请注意,一些编译器,如GCC,不会让你抛弃这样的常量状态。

Note that some compilers, such as GCC, will not allow you to cast away const status like this.

这篇关于更改C常量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆