先从第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上看到的)