c++中const變量真的不可以修改嗎?
在學(xué)c++的時(shí)候,看到的大部分的書籍對const關(guān)鍵字的介紹都是:const關(guān)鍵字修飾的變量的值是不可被修改的。但是事實(shí)真是如此嗎?今天做了一個(gè)小的實(shí)驗(yàn),發(fā)現(xiàn)const變量是可以被修改的。c++代碼如下:
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 const int a = 3;
7 int* p = const_cast<int*>(&a);
8 *p = 4;
9 cout << "value of p: " << *p << endl;
10 cout << "value of a: " << a << endl;
11 cout << "address of p: " << p << endl;
12 cout << "address of a: " << &a << endl;
13
14 return 0;
15 }
上面代碼第7行將a的地址賦值給指針p,然后第8行修改p所指向的地址中的值,運(yùn)行結(jié)果如下:
如上所示結(jié)果,指針p所指向的地址和變量a的地址相同,但是p所指地址中的值已經(jīng)發(fā)生改變。但是為何變量a對應(yīng)的地址中的值已經(jīng)由3變?yōu)?,但是a的值確實(shí)3呢?
暫時(shí)把這個(gè)問題擱淺。再來看一下如下的c++代碼:
1 #include <iostream>
2 using namespace std;
3 const int a = 3;
4 int main()
5 {
6 //const int a = 3;
7 int* p = const_cast<int*>(&a);
8 *p = 4;
9 cout << "value of p: " << *p << endl;
10 cout << "value of a: " << a << endl;
11 cout << "address of p: " << p << endl;
12 cout << "address of a: " << &a << endl;
13
14 return 0;
15 }
如上代碼g++編譯通過,在運(yùn)行時(shí)報(bào)錯(cuò)如下:
由此可見,在c++中全局const變量和局部const變量的編譯器處理的方法是不一樣的。查閱資料得知,全局const變量是不分配內(nèi)存地址的,它編譯器放置在符號(hào)表中作為編譯期常量,全局const變量放在只讀數(shù)據(jù)段中,受到只讀數(shù)據(jù)段的權(quán)限保護(hù),當(dāng)你修改一個(gè)只讀數(shù)據(jù)段中的內(nèi)容時(shí),會(huì)得到一個(gè)運(yùn)行時(shí)錯(cuò)誤。而局部const變量是放在堆棧之中,因?yàn)樵趦?nèi)存中有地址,通過修改地址中的值可以達(dá)到修改const所指內(nèi)存中值的目的。