scanf 返回成功讀取的項數。利用此特性可驗證輸入:
int a;
while (scanf("%d", &a) == 0) { // 輸入非整數時返回 0
getchar(); // 關鍵:清除緩衝區非法字符
printf("請輸入合法整數: ");
}
原理:非法輸入滯留於 stdin 緩衝區,不清除會導致無限循環。getchar() 逐個吞噬錯誤字符。
無絕對優劣,以「代碼可讀性最高」為準則。
int sumMonth = 0;
switch (month - 1) { // 利用無 break 貫穿累加
case 11: sumMonth += 30;
case 10: sumMonth += 31;
case 9: sumMonth += 30;
case 8: sumMonth += 31;
case 7: sumMonth += 31;
case 6: sumMonth += 30;
case 5: sumMonth += 31;
case 4: sumMonth += 30;
case 3: sumMonth += 31;
case 2: // 2 月閏年判斷
if ((year%4==0 && year%100!=0) || year%400==0)
sumMonth += 29;
else
sumMonth += 28;
case 1: sumMonth += 31;
}
注意:case 標籤內不能直接定義變量(作用域問題),需用 {} 包裹。
// 推薦:常量在左,防止誤寫 = 為 ==
if (5 == a) { ... }
// 字符串比較必須用 strcmp
if (strcmp(str1, str2) == 0) { ... }
#include <stdio.h>:系統目錄搜索(標準庫)#include "myheader.h":先當前目錄,再系統目錄(自定義){} 定義塊作用域| 錯誤現象 | 原因 | 對策 |
|---|---|---|
missing ';' before 'type' | C89 要求變量聲明在塊開頭 | 移至塊頂或改用 C99/C++ 編譯 |
LNK1168: cannot open ...exe for writing | 程序未退出,輸出文件被鎖定 | 關閉運行中的程序再編譯 |
p = malloc(sizeof(T));
if (NULL == p) { // 必須檢查
fprintf(stderr, "OOM\n");
exit(-1);
}
// ... 使用 ...
free(p); // 用完必須釋放
p = NULL; // 防野指針
#define MAX 60:預處理替換,無類型,調試不可見,慎用複雜表達式malloc/free 是 C 標準庫函數;new/delete 是 C++ 運算符,調用構造/析構,兩者不可混用