您的位置:首页 > 其它

关于const变量的一点理解

2010-11-13 16:42 267 查看
无意间看到一题目 是关于const变量的。代如下

const int LENGTH = 1;
const  int * pCInt = &LENGTH;
(int)*pCInt = 2;

cout<<&LENGTH<<" "<<pCInt<<endl;
cout<<LENGTH<<" "<<*pCInt<<endl;


问题是:

pCInt = &LENGTH,

然而后面的输出是1 2

为什么?

一步一步分析,const int *pCInt = & LENGTH;

pCInt 为指向LENGTH地址的值,且为常量。

(int) *pCInt = 2; 实际上等同 const_cast<int>(*pCInt) = 2;

去掉变量的常量属性再赋值。也就是改变了 pCInt 指向的地址的值为2.

即然值为2,那么LENGTH中内存的值也为2,为什么会输出1呢?是不是编译器做了

什么处理?(我当时给出的回答就是编译器做出了处理,具体是什么不清楚)

后来仔细想了下,可能是符号替换,不知道对不。

下面用汇编代码来验证我们的想法。

(为了看得清楚,把cout改成printf了)
const int LENGTH = 1;
0040101E  mov         dword ptr [LENGTH],1
const  int * pCInt = &LENGTH;
00401025  lea         eax,[LENGTH]
00401028  mov         dword ptr [pCInt],eax
(int)*pCInt = 2;
0040102B  mov         eax,dword ptr [pCInt]
0040102E  mov         dword ptr [eax],2

//	cout<<&LENGTH<<" "<<pCInt<<endl;
//	cout<<LENGTH<<" "<<*pCInt<<endl;
printf("%X/n",&LENGTH);
00401034  lea         eax,[LENGTH]
00401037  push        eax
00401038  push        offset string "%X/n" (4452A0h)
0040103D  call        printf (401630h)
00401042  add         esp,8
printf("%X/n",pCInt);
00401045  mov         eax,dword ptr [pCInt]
00401048  push        eax
00401049  push        offset string "%X/n" (4452A0h)
0040104E  call        printf (401630h)
00401053  add         esp,8
printf("%d/n",LENGTH);
00401056  push        1
00401058  push        offset string "%d/n" (44529Ch)
0040105D  call        printf (401630h)
00401062  add         esp,8
printf("%d/n",*pCInt);
00401065  mov         eax,dword ptr [pCInt]
00401068  mov         ecx,dword ptr [eax]
0040106A  push        ecx
0040106B  push        offset string "%d/n" (44529Ch)
00401070  call        printf (401630h)
00401075  add         esp,8


从printf("%d/n",LENGTH);

00401056 push 1

可以看出,编译器是做的符号替换,就是在编译的时候遇到LENGHT直接替换为1

printf("%d/n",*pCInt);

00401065 mov eax,dword ptr [pCInt]

00401068 mov ecx,dword ptr [eax]

遇到*pCInt是直接从内存中去取值。

总结如下:

1.变量本身的类型最好不要去改变,除非必要。

2.要明确cosnt的意义,什么时候该用,什么时候不该用,这是基本功。

3.理解符号替换,就相当于宏定义
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: