Re: [討論] 請板友幫忙review置底13誡--N.01

作者: wtchen (沒有存在感的人)   2016-04-16 18:56:38
先從第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上看到的)
作者: Frozenmouse (*冰之鼠*)   2016-04-16 19:13:00
http://stackoverflow.com/questions/1358400這邊有人提到 internal linkagecopy 錯了,我要連的是第一個答案 Orz不過我覺得01講的重點是要養成手動初始化變數的習慣剩下的作為補充資料即可
作者: tinlans ( )   2016-04-16 20:45:00
shall be initizlied (...) before program startupinitialized不要因為中間有個括號,before program startup 就漏了XD
作者: wtchen (沒有存在感的人)   2016-04-16 21:17:00
所以不一定是0?

Links booklink

Contact Us: admin [ a t ] ucptt.com