首頁  >  文章  >  後端開發  >  靜態變數在C/C++中儲存在哪裡?

靜態變數在C/C++中儲存在哪裡?

王林
王林轉載
2023-09-15 21:09:031253瀏覽

靜態變數在C/C++中儲存在哪裡?

靜態變數是程式運行時保留在記憶體中的變量,即它們的生命週期是整個程式運行的時間。這與自動變數不同,它們僅在函數運行時保留在記憶體中,並在函數結束時被銷毀。

靜態變數儲存在記憶體的資料段中。資料段是程式虛擬位址空間的一部分。

所有沒有明確初始化或初始化為零的靜態變數都儲存在未初始化資料段(也稱為未初始化資料段)中。 BSS 段)。與此相比,初始化的靜態變數儲存在初始化的資料段中。

範例如下-

static int x = 5;
static int y;

The static variable x is stored in the initialized data segment and the static variable y is stored in the BSS segment.

示範C 語言靜態變數的程式如下-

範例

 現場示範

#include<stdio.h>
int func(){
   static int i = 4 ;
   i++;
   return i;
}

int main(){
   printf("%d\n", func());
   printf("%d\n", func());
   printf("%d\n", func());
   printf("%d\n", func());
   printf("%d\n", func());
   printf("%d\n", func());

   return 0;
}

上述程式的輸出如下-

5
6
7
8
9
10

現在讓我們理解上面的程式。

在函數func()中,i是靜態變量,被初始化為4。因此它儲存在初始化資料段中。然後 i 遞增並傳回其值。顯示這一點的程式碼片段如下 -

int func(){
   static int i = 4 ;
   i++;
   return i;
}

在函數main()中,函數func()被呼叫6次,它會傳回列印的i的值。由於 i 是靜態變量,因此在程式運行時它會保留在記憶體中並提供一致的值。顯示這一點的程式碼片段如下 -

printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());

以上是靜態變數在C/C++中儲存在哪裡?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除