Kodewick
開始學 →
作用域和 static9 / 30

C 語言作用域和 static

第 9 課,共 30 課 · 第 2 部分 · 函式和陣列 · 約 15 分鐘

C 語言的區域性變數只在所在的 { } 裡有效,函式外定義的是全域性變數;static 區域性變數只初始化一次,函式返回後值還保留著。

一個變數在哪些地方能用,叫它的作用域。到現在為止,變數都寫在函數裡面,它們只在這個函數裡能用。兩個函式可以各有一個同名的變數,互不相干:

main.c
1#include <stdio.h>2 3void morning(void) {4    int steps = 3200;5    printf("上午:%d 步\n", steps);6}7 8void evening(void) {9    int steps = 5100;10    printf("晚上:%d 步\n", steps);11}12 13int main(void) {14    morning();15    evening();16    return 0;17}
輸出
上午:3200 步
晚上:5100 步
整個檔案#include <stdio.h>
morning()int steps = 3200;
evening()int steps = 5100;
每個函式是自己的一個框:兩個 steps 各在各的框裡,互不相干
單選

morning 和 evening 裡各有一個 int steps,它們是什麼關係?

區域性變數

寫在函數裡面的變數叫區域性變數。每次呼叫函式,它就新建出來;函式一結束,它就沒了。別的函式看不見它,main 也不行:

main.c
1#include <stdio.h>2 3void add_tax(int price) {4    int total = price + price / 10;5    printf("含稅:%d\n", total);6}7 8int main(void) {9    add_tax(200);10    printf("%d\n", total);11    return 0;12}
輸出
main.c: In function 'main':
main.c:10:20: error: 'total' undeclared (first use in this function)
   10 |     printf("%d\n", total);
      |                    ^~~~~
main.c:10:20: note: each undeclared identifier is reported only once for each function it appears in

total 只活在 add_tax 裡。到了 main,編譯器根本不認識這個名字:'total' undeclared,意思是「total 沒宣告過」。引數也是區域性變數,price 同樣只在 add_tax 裡能用。

要把結果交給 main,就用第 8 課學過的 return。

單選

函式的引數,在 main 裡能直接用嗎?

程式碼區塊裡的變數

不只是函式,任何一對花括號 { } 都是一個程式碼區塊。在程式碼區塊裡宣告的變數,出了這對花括號就不能用了:

main.c
1#include <stdio.h>2 3int main(void) {4    int hours = 10;5    if (hours > 8) {6        int extra = hours - 8;7        printf("加班 %d 小時\n", extra);8    }9    printf("一共 %d 小時,加班 %d 小時\n", hours, extra);10    return 0;11}
輸出
main.c: In function 'main':
main.c:9:51: error: 'extra' undeclared (first use in this function)
    9 |     printf("一共 %d 小時,加班 %d 小時\n", hours, extra);
      |                                                   ^~~~~
main.c:9:51: note: each undeclared identifier is reported only once for each function it appears in

extra 是在 if 的程式碼區塊裡宣告的,第 9 行已經在程式碼區塊外面了。要在外面用,就把它宣告在外面,比如在 if 前面寫 int extra = 0;。for (int i = 0; ...) 裡的 i 也一樣,只在這個迴圈裡有。

單選

for (int i = 0; i < 3; i++) { … } 結束以後,緊接著寫 printf("%d\n", i); 會怎樣?

練習 1

運費

這段程式編譯不過。改好它:訂單滿 100 元免運費,否則運費 12 元。程式要顯示 運費:12。

要顯示
運費:12
exercise1.c
1#include <stdio.h>2 3int main(void) {4    int amount = 85;5    if (amount < 100) {6        int shipping = 12;7    }8    printf("運費:%d\n", shipping);9    return 0;10}
輸出
點「執行」或按 Ctrl+Enter

全域性變數

寫在所有函式外面的變數叫全域性變數。從它宣告的地方往下,所有函式都能用它,它從程式開始一直活到程式結束:

main.c
1#include <stdio.h>2 3int visitors = 0;4 5void welcome(void) {6    visitors++;7    printf("歡迎,你是第 %d 位客人\n", visitors);8}9 10int main(void) {11    welcome();12    welcome();13    welcome();14    printf("今天一共 %d 位\n", visitors);15    return 0;16}
輸出
歡迎,你是第 1 位客人
歡迎,你是第 2 位客人
歡迎,你是第 3 位客人
今天一共 3 位

welcome 和 main 用的是同一個 visitors。點單步看看:全域性變數不在任何一個函式的堆疊幀裡,它單獨放著,哪個函式改了它,大家看到的都是新值。

全域性變數要是沒寫初始值,會自動是 0。區域性變數不會,沒賦值就用是錯的(第 2 課講過)。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <stdio.h>2 3int total;4 5void add(int n) {6    total += n;7}8 9int main(void) {10    add(4);11    add(6);12    printf("%d\n", total);13    return 0;14}

同名遮住

裡面的作用域可以宣告一個和外面同名的變數。這時在裡面,這個名字指的是裡面的變數,外面那個被遮住了,暫時看不見。函數裡的變數能遮住全域性變數,程式碼區塊裡的變數也能遮住外面的變數。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <stdio.h>2 3int count = 100;4 5int main(void) {6    int count = 5;7    count++;8    printf("%d\n", count);9    return 0;10}

比如在 if 的程式碼區塊裡再宣告一個 score,程式碼區塊裡用的就是它;出了程式碼區塊,外面那個又回來了:

main.c
1#include <stdio.h>2 3int main(void) {4    int score = 70;5    if (score < 80) {6        int score = 80;7        printf("程式碼區塊裡:%d\n", score);8    }9    printf("程式碼區塊外:%d\n", score);10    return 0;11}
輸出
程式碼區塊裡:80
程式碼區塊外:70

能寫不等於該寫。兩個同名的變數很容易看混,最好起不同的名字。

練習 2

購物車

add 把價格加到全域性的 total 上,可程式最後顯示的是 合計:0。找出原因,改好它,讓程式顯示 合計:60。

要顯示
合計:60
exercise2.c
1#include <stdio.h>2 3int total = 0;4 5void add(int price) {6    total = total + price;7}8 9int main(void) {10    int total = 0;11    add(25);12    add(35);13    printf("合計:%d\n", total);14    return 0;15}
輸出
點「執行」或按 Ctrl+Enter

static 區域性變數

普通區域性變數每次呼叫都重新建,上次的值留不下來。比如這個 press,它的 count 每次都從 0 開始,所以總是顯示 1:

main.c
1#include <stdio.h>2 3void press(void) {4    int count = 0;5    count++;6    printf("按了 %d 次\n", count);7}8 9int main(void) {10    press();11    press();12    press();13    return 0;14}
輸出
按了 1 次
按了 1 次
按了 1 次

在宣告前面加上 static,它就成了 static 區域性變數:只有這個函式能用(作用域還是區域性的),但它和全域性變數一樣,從程式開始活到結束。= 0 只在最開始做一次,以後每次呼叫,它都記得上次的值:

main.c
1#include <stdio.h>2 3void press(void) {4    static int count = 0;5    count++;6    printf("按了 %d 次\n", count);7}8 9int main(void) {10    press();11    press();12    press();13    return 0;14}
輸出
按了 1 次
按了 2 次
按了 3 次

兩個 press 都點單步比一比:沒有 static 的,每次呼叫,堆疊幀裡都有一個新的 count,從 0 開始;加了 static 的,count 不在堆疊幀裡,函式結束了它也還在,下次呼叫接著往上加。

普通區域性變數int count = 0; count++;1 → 1 → 1每次呼叫都新建一個
static 區域性變數static int count = 0; count++;1 → 2 → 3= 0 只在最開始做一次
同樣呼叫 3 次 press:普通區域性變數每次都從 0 開始,static 的記得上次的值
猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <stdio.h>2 3int next(void) {4    static int n = 10;5    n += 5;6    return n;7}8 9int main(void) {10    next();11    next();12    printf("%d\n", next());13    return 0;14}
練習 3

取號

next_ticket 每呼叫一次,應該返回下一個號:1、2、3……現在它每次都返回 1。改好它,讓程式顯示 1 號、2 號、3 號,各佔一行。

要顯示
1 號
2 號
3 號
exercise3.c
1#include <stdio.h>2 3int next_ticket(void) {4    int number = 0;5    number++;6    return number;7}8 9int main(void) {10    printf("%d 號\n", next_ticket());11    printf("%d 號\n", next_ticket());12    printf("%d 號\n", next_ticket());13    return 0;14}
輸出
點「執行」或按 Ctrl+Enter

少用全域性變數

全域性變數用著方便,可是誰都能改它。程式一長,一個值不對了,就得把所有函式都查一遍,才知道是誰改的。比如這個程式想打 3 行星號,main 和 print_stars 卻共用了一個全域性的 i:

main.c
1#include <stdio.h>2 3int i;4 5void print_stars(int n) {6    for (i = 0; i < n; i++) {7        printf("*");8    }9    printf("\n");10}11 12int main(void) {13    for (i = 0; i < 3; i++) {14        print_stars(5);15    }16    return 0;17}
輸出
*****

只打了 1 行。print_stars 跑完,i 已經是 5 了;回到 main,i++ 變成 6,i < 3 不成立,迴圈就結束了。點單步,盯著 i 看。把 int i; 刪掉,兩個迴圈各寫 for (int i = 0; ...),各用各的區域性變數,就對了。

小技巧: 一個函式需要的值,儘量用引數傳進去;算出來的結果,用 return 交回來。這樣看函式的第一行,就知道它用什麼、交出什麼。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <stdio.h>2 3int i;4 5void twice(void) {6    for (i = 0; i < 2; i++) {7        printf("*");8    }9}10 11int main(void) {12    for (i = 0; i < 3; i++) {13        twice();14    }15    printf("\n");16    return 0;17}

這一課學會了

  • 作用域就是變數能用的範圍。
  • 函數裡和程式碼區塊裡宣告的是區域性變數,只在自己的花括號裡能用;引數也是區域性變數。
  • 函式外面宣告的是全域性變數,所有函式都能用,沒寫初始值就是 0。
  • 裡面宣告的同名變數會遮住外面的;最好別這樣起名。
  • static 區域性變數只在自己的函數裡能用,但會一直活著,記住上次的值。
  • 少用全域性變數:需要的值用引數傳進去,結果用 return 交回來。
第 9 課學完了嗎?第 9 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 10 課 · 15 分鐘遞迴學 C 語言遞迴:函式呼叫自己、終止條件、階乘和斐波那契、單步看堆疊幀一層層疊起來再退回去、沒有終止條件會怎樣,以及遞迴和迴圈怎麼選。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。