每宣告一個變數,它就會被配置一個專屬的記憶體空間。 專屬表示記憶體空間不會被挪為他用,且記憶體空間有限 不同的變數,生存空間(Life Scope)、生存時間(Life Cycle)各不相同 生存空間(Life Scope):變數可以被使用的程式碼區段 ## 1. 變數種類與功能 ### 1. 區域變數(local variable)(自動變數automatic variable) (1) 宣告在大括號內,生於宣告,死於下括號 (2) 在同一區塊(block)內不可宣告同名的區域變數 (3) 在變數的可視範圍外不可使用該變數 ```cpp= for(int i=0;i<10;i++) { int a; //配置記憶體 //do sth... } //釋放記憶體 cout<<i<<" "<<a<<endl; //報錯 ``` ### 2. 全域變數(global variable) (1) 宣告在任何block之外的變數 (2) 若沒有賦予初始值,則自動給0 (3) 在程式碼結束前都能使用 (4) 任何block都能使用 ### 3. 靜態變數(static variable) (1) 用關鍵字static修飾變數 (2) 若沒有賦予初始值,則自動給0 (3) 在程式碼結束前都會占用記憶體 (4) 如同global variable一直存在,但static variable不能在任何區段存取 ```cpp= #include <bits/stdc++.h> using namespace std; void count(int i,int End) { static int x=0; int y=0; x++; y++; if(i==(End-1)) { cout<<"x="<<x<<endl; cout<<"y="<<y<<endl; } } int main() { ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); for(int i=0;i<5;i++) count(i,5); return 0; } //x=5,y=1 ``` 原因:count函式會對x,y配置記憶體,當count函式結束時,會將y的記憶體歸還,而x被宣告為int static,x的記憶體不會歸還,沿用上次的值。 ## 2. 變數遮蔽 當程式碼內變數撞名時,範圍小的變數會暫時遮蔽範圍大的變數 ```cpp= #include <bits/stdc++.h> using namespace std; int main() { for(int i = 0; i < 10; i++){ cout << "i = " << i << " outside, "; for(int i = 0; i< 10 ;i++){ cout << i*i << ' '; } cout << endl; } return 0; } ``` ![](https://hackmd.io/_uploads/B17mlEHK3.png) 原因:外層的i與內層的i不相同 ## 3. 修飾子 - 改變所佔的記憶體空間 short、long - 改變數值範圍 unsigned - 不可更動常數 const ### (1) 改變記憶體所占空間 | 修飾子名稱 | 記憶體空間 | 數值範圍 | | --- | --- | --- | | short int | 2 byte | -32678~32767 | | int | 4 byte | 2e31-1 約 2*10e9 | | long int | 4 byte | 2e31-1 | | long long int | 8 byte | 2e63-1 約 9*10e9 | #include <limits.h> 定義了整數型別的上下限 ```cpp= #include <limits.h> #include <bits/stdc++.h> using namespace std; int main(void) { cout << "Max of short: "<< SHRT_MAX << endl; cout << "Min of short: "<< SHRT_MIN << endl; cout << endl; cout << "Max of int: "<< INT_MAX << endl; cout << "Min of int: "<< INT_MIN << endl; cout << endl; cout << "Max of long: "<< LONG_MAX << endl; cout << "Min of long: "<< LONG_MIN << endl; cout << endl; cout << "Max of long long: "<< LLONG_MAX << endl; cout << "Min of long long: "<< LLONG_MIN << endl; cout << endl; return 0; } ``` ![](https://hackmd.io/_uploads/SJVMx4Ht3.png) 溢位 overflow :數值超過該型態所能表示的範圍 ### (2)改變數值範圍 加上關鍵字unsigned,變成無號變數 數值>=0,表示範圍變為原本的兩倍 ```cpp=![](https://hackmd.io/_uploads/Sk6-kESFn.png) #include <limits.h> #include <bits/stdc++.h> using namespace std; int main(void) { cout << "Max of unsigned short: "<< USHRT_MAX << endl; cout << endl; cout << "Max of unsigned int: "<< UINT_MAX << endl; cout << endl; cout << "Max of unsigned long: "<< ULONG_MAX << endl; cout << endl; cout << "Max of unsigned long long: "<< ULLONG_MAX << endl; cout << endl; return 0; } ``` ![](https://hackmd.io/_uploads/rJqxxVBKh.png) ### (3) 不可更動常數 宣告時加上關鍵字 const(constant) 宣告時必須初始化 值不能被修改 適合用在變數值不會被更動時 修飾子可以用很多個 ```cpp= const unsigned long long a=0; const short int b=0; const static c=0; const unsigned long long int d=0; ```