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