全域變數與靜態 (static) 區域變數

學習筆記
Nov 2, 2020

--

全域變數 : 在函式定義之外宣告、定義變數。可以讓不同函式使用同一個。每次/不同函式呼叫使用同一個,只會在一開始initial一次。

區域變數 : 在區域/函式中作定義 每次呼叫函式都是獨立一份(初始一次)。

Staic 區域變數 : 在區域/函式中變數達到全域變數效果。讓區域變數重複呼叫函式也只會有一份變數不會initial。

Exercise

In this exercise, try to find the sum of some numbers by using the static keyword. Do not pass any variable representing the running total to the sum() function.呼

呼叫函式sum()三次 , 三次輸入值作累加。呼叫三次print三次。

#include <stdio.h>//方法一:全域變數定義在函式之外
int numb;
int sum (int num) {

//方法二:靜態區域變數
static int numb;

numb = numb + num;
return numb;
}
int main() {
printf("%d \n",sum(55));
printf("%d \n",sum(45));
printf("%d \n",sum(50));
return 0;
}

Output

55 
100
150

--

--