这个题一定要注意是在C++中的运行结果。
在C语言中
1
2
3
4
5
6
7
|
void
main(){ const
int
i = 0; int
*j = ( int
*)&i; *j
= 1; printf ( "%d,%d" ,
i, *j); system ( "pause" ); } |
结果输出为1,1
在C++中
1
2
3
4
5
6
7
8
9
10
|
#include<iostream> using
namespace
std; int
main( void ){ const
int
i=0; int
*j = ( int
*)&i; *j
= 1; printf ( "%d,%d" ,
i, *j); system ( "pause" ); return
0; } |
结果输出为0,1
分析:C语言中的const是运行时const,编译时只是定义,在运行才会初始化。C语言中const变量不能用于成为数组长度等作为编译时常量的情况,原因就在此。C语言const变量在运行时改变了是可以再次读出改变后的值的。
C++中,const变量是编译时的常量,可以向#define定义的常量一样使用。故C++中const变量的值在编译时就已经确定了,直接对cosnt变量进行了值的替换,因此当const变量的值改变时,const的变量值是不会得到更新的。
这几行代码在C和C++中都会改变const变量的值,只不过C++中const变量在编译的时候已经确定了,而C中的const变量可以在运行时改变后再次读取。以下代码核实了C++中的const变量确实被改变了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#include<stdio.h> #include<iostream> using
namespace
std; int
main( void ){ const
int
i=0; int
*j = ( int
*)&i; *j
= 1; printf ( "%d,%d\n" ,
i, *j); cout
<< "i
address" <<&i
<< endl; cout
<< "j
address" <<j
<< endl; return
0; } |

同一个地址,即同一个变量。C++中const变量确实别改变了。i的值没有更新而已。