Turbo C 2.0 依宣告位置將變數分為三類,掌握其差異是模組化程式設計的基礎。
void demo(void)
{
int i; /* 隱式 auto */
auto int j; /* 顯式 auto (極少使用) */
/* ... */
}
/* 宣告 */
void puthz(int x, int y, int color, char *p);
/* 定義 */
void puthz(int x, int y, int color, char *p)
{
int i, j, k; /* 區域變數 */
/* 函數本體 */
}
const。
#include <stdio.h>
int test = 0; /* 定義於所有函數外部 */
void f1(int x, float y);
void f2(void);
int main(void)
{
test = 5;
f1(20, 5.5f); /* test 變 115 */
f2(); /* test 變 1150 */
return 0;
}
void f1(int x, float y)
{
float z = x * y;
test += (int)z; /* 直接讀寫全域 */
}
void f2(void)
{
int count = 10;
test *= count;
}
extern 可跨檔案存取。#include 之後、main 之前。| 特性 | 區域 | 形式參數 | 全域 |
|---|---|---|---|
| 儲存區 | 堆疊 | 堆疊 | 靜態區 (.data/.bss) |
| 預設初值 | 不定 (垃圾值) | 由呼叫端傳入 | 0 |
| 可見範圍 | 定義區塊內 | 函數本體內 | 全程 (含跨檔) |
| 存活期 | 函數執行期間 | 函數執行期間 | 程式全程 |
| 執行緒安全 | 是 (各呼叫獨立) | 是 | 否 (需鎖/原子操作) |
雖可「免傳參」共享資料,但缺點明顯:
static 限制連結:檔案內全域變數預設加 static,避免汙染全域命名空間。get_xxx()/set_xxx(),集中加入斷言、日誌、鎖。