C++ 中靜態變數、自動變數、全域性變數和區域性變數的區別


這裡有兩個獨立的概念:

  • 作用域,決定名稱可以在哪裡被訪問 - 全域性和區域性
  • 儲存期,決定變數何時建立和銷燬 - 靜態和自動

作用域

區域性變數只能被該函式或程式碼塊內部的語句使用。區域性變數對於函式本身來說是未知的。

示例

即時演示

#include <iostream>
using namespace std;

int main () {
   // Local variable declaration:
   int a, b;
   int c;

   // actual initialization
   a = 10;
   b = 20;
   c = a + b;

   cout << c;
   return 0;
}

這將給出以下輸出:

輸出

30

全域性變數定義在所有函式之外,通常位於程式的頂部。全域性變數將在程式的整個生命週期內保持其值。任何函式都可以訪問全域性變數。

示例

即時演示

#include <iostream>
using namespace std;

// Global variable declaration:
int g;

int main () {
   // Local variable declaration:
   int a, b;

   // actual initialization
   a = 10;
   b = 20;
   g = a + b;

   cout << g;
   return 0;
}

這將給出以下輸出:

輸出

30

儲存期

自動變數是區域性變數,其生命週期在執行離開其作用域時結束,並在重新進入作用域時重新建立。

示例

for (int i =0 0; i < 5; ++i) {
   int n = 0;
   printf("%d ", ++n); // prints 1 1 1 1 1 - the previous value is lost
}

靜態變數的生命週期持續到程式結束。如果它們是區域性變數,則它們的值在執行離開其作用域時會保留。

for (int i = 0; i < 5; ++i) {
   static int n = 0;
   printf("%d ", ++n); // prints 1 2 3 4 5 - the value persists
}

請注意,static 關鍵字除了靜態儲存期之外還有多種含義。此外,在 C++ 中,auto 關鍵字不再表示自動儲存期;它現在表示自動型別,從變數的初始化程式中推斷得出。

更新時間: 2019-07-30

3K+ 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告