摘自http://zhidao.baidu.com/question/120216130.html的const若干使用问题

本文通过几个测试案例探讨了C++中const变量的行为特性,特别是当尝试通过指针改变其值时的情况。揭示了编译器对const变量的优化方式及其潜在的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include
#include

using std::cout;
using std::endl;
void changeValue( const int *a );

int main()
{
//test 1
        const int test = 9;
    changeValue( &test );
    cout<<

//test 2
        int test31 = 10;
    const int test3 = test31;
    changeValue( &test3 );
    cout<<

//test 3
        int test1 = 10;
    changeValue( &test1 );
    cout<<

//test4
        int s = 30;
    const int tag = s;
    const int *cp = &tag;
    *(int*)cp = 10;
    cout<<<","<<*cp<

//test 5
        const int tag1 = 30;
    const int *cp1 = &tag1;
    *(int*)cp1 = 10;
    cout<<<","<<*cp1<

        return 0;
}

void changeValue( const int *a )
{
    *(int*)a = 0;
}

output:

9
0
0
10,10
30,10

下面是解释:

你把一个变量声明成const类型,就意味着你不会更改它的值,编译器能保证其不被直接修改,可能就放松了对它的控制。比如第一次访问时读到寄存器里,下次在访问时如果还在寄存器中,就不会再从内存中读取。const类型的变量不是在只读内存里的,他也是栈或者堆或者全局的可读写内存里的,如果中间你通过间接的手段改动了内存中的值(程序可读写内存里面的东西,一般没有保护,可以通过指针随便改的),编译器可能觉察不到,仍是用寄存器中的值,就会产生一些微妙的现象。

证实:

通过调试都可以看出来,const类型变量内存中值是改了的。

通过程序也可以看出,通过取地址然后复引用,输出的结果就是更改之后的:
#include

using namespace std;

int main()
{
 {
  const int i = 0;
  *(int*)&i = 1;
  cout << i << "/t" << *(int*)&i << endl;
 }
 {
  const int i = 0;
  const int j = i;
  *(int*)&j = 1;
  cout << j << "/t" << *(int*)&j << endl;
 }
 {
  const int i = 0;
  const int* j = &i;
  *(int*)j = 1;
  cout << i << "/t" << *j << endl;
 }
    return 0;
}

通过汇编可以看出,编译器直接把常变量的值替换成了常量,而没有读到寄存器或者从内存中读取,而普通变量,是从内存中读取的:

8:            const int i = 0x12345678;
004017A8   mov         dword ptr [i],12345678h
9:            int j = i;
004017AF   mov         dword ptr [j],12345678h
10:           int k = i + j;
004017B6   mov         eax,dword ptr [j]       //here
004017B9   add         eax,12345678h          //here
004017BE   mov         dword ptr [k],eax 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值