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

程式可以為區域性變數和全域性變數使用相同的名稱,但是函式內部區域性變數的值將優先。要訪問具有相同名稱的全域性變數,必須使用作用域解析運算子。

示例

#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main () {
   // Local variable declaration:
   int g = 10;

   cout << g;   // Local
   cout << ::g; // Global
   return 0;
}

輸出

這將輸出:

10
20

更新於:2020年2月11日

8K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告