自动初始化局部变量 [英] Auto Initialization of local variables
问题描述
我有以下代码段.
int j;
printf("%d",j);
如预期的那样,我得到一个垃圾值.
As expected, I get a garbage value.
32039491
32039491
但是当我在上面的代码段中包含一个循环时,例如
But when I include a loop in the above snippet, like
int j;
print("%d",j);
while(j);
在该程序的多次试用中,我得到了以下输出.
I get the following output on multiple trials of the program.
0
我一直认为本地变量默认情况下会初始化为垃圾值,但是看起来像使用循环时变量会自动初始化.
I always thought local variables are initialized to a garbage value by default, but it looks like variables get auto initialized when a loop is used.
推荐答案
它具有不确定的值.可以是任何东西.
It is having indeterminate value. It can be anything.
引用C11
§6.7.9
如果未自动初始化具有自动存储期限的对象,则其值为 不定. [...]
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [...]
除非明确初始化,否则自动局部变量将包含不确定的值.如果您尝试在变量具有不确定值的情况下尝试使用该变量,并且
Automatic local variables, unless initialized explicitly, will contain indeterminate value. In case you try to use a variable while it holds indeterminate value and either
- 没有地址
- 可以有陷阱表示
该用法将导致不确定的行为.
这篇关于自动初始化局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!