C和C++中都有const关键字,但处理方式有一些差别,先看看下面两个示例程序:
/*
* test.c, compiled with: gcc -o test test.c
*
*/
#include <stdio.h>
int main(int argc, char **argv)
{
const int a = 100;
int *p = (int *)&a;
*p = 200;
printf("%d\n", a);
printf("%d\n", *p);
}
运行之后的输出结果为:
200
200
/* test.cpp, compiled with: g++ -o test test.cpp */
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
const int a = 100;
int *p = (int *)&a;
*p = 200;
cout << a << endl;
cout << *p << endl;
}
运行结果为:
100
200
之所以两个程序中输出a的结果有差异,就是因为在C语言中const类型的数据在程序运行时会去访问内存找到a对应内存中的值,而该内存单元被指针间接改变了。
而在C++中,在编译时所有直接对a的引用都被替换成100,运行时不再访问内存了,效果相当于#define a 100,区别就是宏定义中a没有内存单元,但const定义时a有内存单元。