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
廣告