先從第1誡開刀: 01. 你不可以使用尚未給予適當初值的變數 錯誤例子: int accumulate(int max) /* 從 1 累加到 max,傳回結果 */ { int sum; /* 未給予初值的區域變數,其內容值是垃圾 */ int num; for (num = 1; num <= max; num++) { sum += num; } return sum; } 正確例子: int accumulate(int max) { int sum = 0; /* 正確的賦予適當的初值 */ int num; for (num = 1; num <= max; num++) { sum += num; } return sum; } ================================================================ 應該修改的地方: - 如果變數不為以下屬性(預設為auto)或動態配置(malloc), 其初始值為undefined behavior: * static * _Thread_local * global variable (這個我在Standard沒找到) Standard對應部份: 5.1.2 Execution environments 1. ... All objects with static storage duration shall be initialized (set to their initial values) before program startup. The manner and timing of such initialization are otherwise unspecified. Program termination returns control to the execution environment. 靜態儲存(static storage duration,怎麼翻比較好阿?)的物件必須被初始化 並給予初始值,其他不用(其他的就是第1誡所表達的) 6.2.4 Storage durations of objects 3. An object whose identifier is declared without the storage-class specifier _Thread_local (C11新增?), and either with external or internal linkage(這啥?) or with the storage-class specifier static, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup. static storage duration 包含: - _Thread_local (C11新增?) - 含有static 修飾字的變數 不過這邊似乎沒提到global variable也是被初始化為0.... (這是我在Deep C的slide上看到的)