Auto Initialization of local variables

时间秒杀一切 提交于 2019-12-17 21:59:13

问题


I have the following code snippet.

int j;
printf("%d",j);

As expected, I get a garbage value.

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.


回答1:


It is having indeterminate value. It can be anything.

Quoting 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

  • does not have the address taken
  • can have trap representation

the usage will lead to undefined behavior.




回答2:


As expected, I get a garbage value.

Then your expectation is unjustifiably hopeful. When you use the indeterminate value of an uninitialized object, you generally get (and for your code snippets alone you do get) undefined behavior. Printing a garbage value is but one of infinitely many possible manifestations.

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.

You thought wrong, and you're also drawing the wrong conclusion. Both of your code snippets, when standing alone, exhibit undefined behavior. You cannot safely rely on any particular result.



来源:https://stackoverflow.com/questions/41735515/auto-initialization-of-local-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!