C語言中的全域性變數



全域性變數

在C程式語言中,**全域性變數**是在所有函式之外定義的變數,通常位於程式的頂部。變數。**全域性變數**在程式的整個生命週期中保持其值,並且可以在為程式定義的任何函式內部訪問。

如果一個函式訪問並修改全域性變數的值,則更新後的值可用於其他函式呼叫。

如果一個變數在某個檔案中定義,則仍然可以透過使用**extern**關鍵字在另一個程式碼模組中將其訪問為全域性變數。**extern**關鍵字也可以用來訪問**全域性變數**而不是同名的區域性變數。

宣告全域性變數

在C中宣告全域性變數類似於宣告普通的(區域性)變數,但全域性變數是在函式之外宣告的。

語法

考慮以下宣告全域性變數的語法

data_type variable_name;

// main or any function
int main()
{
}

C語言中全域性變數的示例

以下程式展示瞭如何在程式中使用全域性變數

#include <stdio.h>

/* global variable declaration */
int g = 10;

int main(){

   /* local variable declaration */
   int a;

   /* actual initialization */
   a = g * 2;
   printf("Value of a = %d, and g = %d\n", a, g);
   
   return 0;
}

輸出

執行此程式碼時,將產生以下輸出:

Value of a = 20, and g = 10

訪問全域性變數

全域性變數可在C程式中的所有函式中訪問。如果任何函式更新全域性變數的值,則其更新後的值隨後將對所有其他函式可用。

示例

以下示例演示了在C語言中訪問全域性變數的示例

#include <stdio.h>

/* global variable declaration */
int g = 10;

int function1();
int function2();

int main(){

   printf("Value of Global variable g = %d\n", g);
   
   function1();
   printf("Updated value of Global variable g = %d\n", g);
   
   function2();
   printf("Updated value of Global variable g = %d\n", g);
   
   return 0;
}

int function1(){
   g = g + 10;
   printf("New value of g in function1(): %d\n", g);
   return 0;
}

int function2(){  
   printf("The value of g in function2(): %d\n", g);
   g = g + 10;
   return 0;
}

執行程式碼並檢查其輸出:

Value of Global variable g = 10
New value of g in function1(): 20
Updated value of Global variable g = 20
The value of g in function2(): 20
Updated value of Global variable g = 30

全域性變數的作用域和可訪問性

全域性變數僅對在其聲明後定義的函式可用。全域性變數在任何函式之外宣告,因此預設情況下,它們可以被同一檔案中的所有函式訪問。

示例

在這個例子中,我們在main()函式之前聲明瞭一個全域性變數(x)。還有一個全域性變數y,它是在main()函式之後但在function1()函式之前宣告的。在這種情況下,變數y即使是一個全域性變數,也不能在main()函式中使用,因為它是在之後宣告的。結果,你會得到一個錯誤。

#include <stdio.h>

/* global variable declaration */
int x = 10;

int function1();

int main(){

   printf("value of Global variable x= %d y=%d\n", x, y);
   function1();
   return 0;
}

int y = 20;

int function1(){
   printf ("Value of Global variable x = %d y = %d\n", x, y);
}

執行此程式碼時,將產生錯誤:

Line no 11: error: 'y' undeclared (first use in this function)
   11 | printf ("Value of Global variable x = %d y = %d\n", x, y);
      |                                                     ^

使用extern關鍵字訪問全域性變數

如果在程式中同時存在同名的全域性變數和區域性變數,則應使用extern關鍵字。

示例

在這個C程式中,我們有一個全域性變數和一個同名的區域性變數(x)。現在,讓我們看看如何使用“extern”關鍵字來避免混淆:

#include <stdio.h>

// Global variable x
int x = 50;

int main(){

   // Local variable x
   int x = 10;{
      extern int x;
      printf("Value of global x is %d\n", x);
   }

   printf("Value of local x is %d\n", x);

   return 0;
}

輸出

執行此程式碼時,將產生以下輸出:

Value of global x is 50
Value of local x is 10

避免使用全域性變數

**全域性變數**可以簡化程式設計邏輯。它們可以在函式之間訪問,並且不需要使用引數傳遞技術將變數從一個函式傳遞到另一個函式。但是,在C程式中擁有過多的全域性變數並不明智或高效,因為這些變數佔用的記憶體直到程式結束才會釋放。

使用全域性宣告不被認為是一種好的程式設計實踐,因為它沒有實現結構化的方法。出於安全考慮,也不建議使用全域性宣告,因為它們對所有函式都是可訪問的。最後,使用全域性宣告會使程式難以除錯、維護和擴充套件。

廣告