作用域
默認const定義在函數外,則作用域僅在文件內有效
如果希望擴大作用域,則需要在變量定義和聲明之前添加 extern關鍵字。
// file_1.cpp
extern const int maxValue = 1024;
// file_1.h
extern const int maxValue;
特徵
當以編譯時初始化的方式定義一個const對象時,如下面所示
const int maxValue = 1024;
因爲是通過常量表達式初始化,所以編譯器在編譯的時候會把使用該變量的地方替換成對應的值。代碼中所有使用maxValue的地方都會被替換成1024。
可以通過指針來改變const 局部變量的值
不過要注意
const不能是常量表達式。也就是說,不能在編譯階段計算出來。因爲常量表達式的const會在編譯階段直接將使用該const常量表達式的地方替換成const所代表的常量(如上面的maxValue常量)。也就是說在運行階段改變了const局部變量的值,並不會影響使用const常量的語句。因爲這些使用const常量的地方,在編譯階段就已經被替換爲相應的常量表達式。
成功改變const局部變量的例子
#include <iostream>
using namespace std;
int fun()
{
return 1;
}
int main() {
const int a = fun();//使得const變量需要在運行階段才能計算出來。
int* b = (int *)&a;
*b = 31;
cout << a << endl;
return 0;
}
輸出結果爲
31
但是非局部const變量則會出現段錯誤:
#include <iostream>
using namespace std;
int fun()
{
return 1;
}
const int a = 23;
int main() {
//const int a = fun();
int* b = (int *)&a;
*b = 31;
cout << a << endl;
return 0;
}
輸出以下錯誤,也就是有代碼修改了不能修改內存區域
[1] 18284 segmentation fault ./CppLearn