| 結構類型 | 關鍵字 | 適用場景 |
|---|---|---|
| 順序 | 表達式語句、`{}` 區塊 | 單一路徑、線性邏輯 |
| 選擇 | `if`/`else`/`switch` | 條件分支、多路分派 |
| 迴圈 | `for`/`while`/`do-while` | 重複執行、已知/未知次數 |
| 跳轉 | `break`/`continue`/`return`/`goto` | 流程中斷/提前結束 |
| 類別 | 宣告位置 | 作用域 | 儲存期 | 預設初值 |
|---|---|---|---|---|
| 區域自動 | 區塊內 | 宣告處 → 區塊結尾 | 區塊執行期間 | 不定值 |
| 區域靜態 | 區塊內 `static` | 宣告處 → 區塊結尾 | 程式全程 | 0 |
| 全域外部 | 函式外 | 整個專案 (需 `extern`) | 程式全程 | 0 |
| 全域內部 | 函式外 `static` | 僅本轉譯單元 | 程式全程 | 0 |
鐵律:先宣告後使用;區塊內同名遮蔽外層;`static` 區域變數僅初始化一次。
printf("整數:%d 八進位:%o 十六進位:%x 浮點:%f 字串:%s 字元:%c\n", 42, 42, 42, 3.14, "hi", 'A');
/* 寬度/精度/對齊 */
printf("%10d | %-10s | %05d | %.2f\n", 1, "left", 42, 3.14159);
int a; double b; char c;
scanf("%d %lf %c", &a, &b, &c); /* 必須傳址 & */
scanf("%d,%lf", &a, &b); /* 格式字串可含非格式字元匹配輸入分隔符 */
陷阱:`scanf("%d", &a)` 忘記 `&` → 未定義行為;`%f` 對應 `float*`,`%lf` 對應 `double*`。
if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 60) grade = 'C'; else grade = 'F';
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days = 31; break;
case 4: case 6: case 9: case 11:
days = 30; break;
case 2:
days = is_leap(year) ? 29 : 28; break;
default:
days = -1; // 錯誤月份
}
for (int i = 1, sum = 0; i <= 100; ++i) {
sum += i;
}
printf("1+...+100 = %d\n", sum); // i 在此不可見 (C99 區塊作用域)
int sum = 0, i = 1;
while (sum <= 1000) {
sum += i++;
}
printf("首個使和>1000的 n = %d\n", i-1);
int input;
do {
printf("輸入 1-10: ");
scanf("%d", &input);
} while (input < 1 || input > 10);
| 關鍵字 | 效果 | 典型用法 |
|---|---|---|
| `break` | 跳出最內層 `switch`/`for`/`while`/`do-while` | 找到目標提前結束搜尋 |
| `continue` | 跳過本次迴圈剩餘,直接進入下一次迭代 (執行 `for` 的第三表達式) | 跳過無效資料繼續處理 |
| `return` | 離開當前函式,回傳值給呼叫者 | 提前結束函式、錯誤處理 |
| `goto` | 無條件跳轉到同函式內標籤 | 極少用:多層迴圈同時跳出、錯誤清理集中化 |
/* goto 多層跳出範例 */
for (int i=0; i<10; ++i)
for (int j=0; j<10; ++j)
if (found(i,j)) goto DONE;
DONE:
printf("Found at (%d,%d)\n", i, j);
void dealCards(int playerId) { printf("發牌給玩家 %d\n", playerId); }
int main(void) {
for (int round = 1; round <= 27; ++round) {
printf("第 %d 輪\n", round);
for (int id = 1; id <= 4; ++id)
dealCards(id);
}
return 0;
}
流程控制是程式的骨架。熟練掌握「順序、選擇、迴圈、跳轉」四大基本結構,並養成「邊界優先、型別正確、作用域最小」的編碼習慣,能寫出既正確又易維護的 C 程式碼。