关于const变量的一点理解
2010-11-13 16:42
267 查看
无意间看到一题目 是关于const变量的。代如下
问题是:
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了)
从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.理解符号替换,就相当于宏定义
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.理解符号替换,就相当于宏定义
相关文章推荐
- 关于const变量的一点理解
- 我的C++学习日记——关于const数值变量,指针和引用的理解
- 关于JS中变量提升的规则和原理的一点理解(二)
- 关于头文件保护和变量重复定义的一点理解
- 关于JS中变量提升的规则和原理的一点理解(一)
- 关于实例变量的一点理解
- 关于计算机编程的一点理解(2)
- 关于数据库索引的一点理解
- 关于银联支付协议的一点理解
- 关于foreach、Iterable、Iterator的一点理解
- 关于BAYES判别的一点理解
- 关于java中多线程的一点理解
- 关于IAP的一点深入理解
- [转载+实践理解]Android动画---如何正确使用平移动画(关于fillBefore和fillAfter的一点说明)(转载)
- 关于C#.Net中事件(event)、委托(delegate)和方法的一点理解
- 关于C#中Thread.Join()的一点理解
- 初学者关于c语言中函数局部变量空间释放的理解
- 关于委托的一点理解。
- 关于Character的digit,forDigit,getNumericValue方法的一点理解
- 关于NI CompactRIO自定义模块中FPGA与Labview FPGA中编程的一点理解