局部变量的自动初始化 [英] Auto Initialization of local variables

查看:26
本文介绍了局部变量的自动初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码片段.

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.

推荐答案

它具有不确定的价值.它可以是任何东西.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆