问一个关于const变量的问题

来源:百度知道 编辑:UC知道 时间:2024/05/22 19:04:04
int *i;
const int j = 1;
const int *k ;
i = (int *) &j;
*i = 4;
cout << "now j is " << j << ", with address " << &j << endl;
cout << "now *i is " << *i << ", with address " << i << endl;

在VS2005下面测试结果如下:
now j is 1, with address 0012FEE8
now *i is 4, with address 0012FEE8
谢谢大家关注:
问题是:&j 和 i 是同一个地址, 但j 和 *i值却不同,为什么?

to fengzhiyeq:
怎么VS2005的编译器对这两句:
i = (int *) &j;
*i = 4; /////////错误
不报错的呢?

你的问题是啥?
-------------------
其实这个是编译器造成的,因为函数申明的时候j为const,因此在你引用j的时候编译器不会从j的实际地址里取值,而是直接用常数1。当你用&j时编译器会使用j的地址。下面是
cout << "now j is " << j << ", with address " << &j << endl;这句的反汇编:
0040106E push offset @ILT+10(endl) (0040100f)
00401073 lea edx,[ebp-8]
00401076 push edx
00401077 push offset string ", with address " (00428038)
0040107C push 1
0040107E push offset string "now j is " (0042802c)
注意里面有个push 1, 说明用的是直接数1而不是从j的地址里取的值。
对比cout << "now *i is " << *i << ", with address " << i << endl;
004010A9 push offset @ILT+10(endl) (0040100f)
004010AE mov eax,dword ptr [ebp-4]
004010B1 push eax
004010B2 push offset string ", with address " (00428038)
004010B7 mov ecx,dword ptr [ebp-4]