c - 未初始化的变量的值是多少?

标签 c initialization garbage

Possible Duplicate:
Is uninitialized data behavior well specified?

我尝试了以下代码

#include<stdio.h>
void main()
{
int i; \
printf('%d',i);
}

结果在 VC++ 中给出垃圾值,而在 tc 中同样为零。 正确的值是多少? 默认情况下未初始化的变量的值是否为零?或者它会包含垃圾值?

下一个是相同的

#include<stdio.h> 
void main()
{
int i,j,num;
j=(num>0?0:num*num);
printf("\n%d",j);
}

上面代码的输出是什么?

最佳答案

从技术上讲,未初始化的非静态局部变量的值是不确定[引用1]
简而言之,它可以是任何东西。访问此类未初始化的变量会导致未定义的行为[引用资料 2]

[引用 1]
C99 第 6.7.8 节初始化:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

[引用 2]

C99 第 3.18 节未定义行为:

behavior, upon use of a nonportable or erroneous program construct, of erroneous data, or of indeterminately valued objects, for which this International Standard imposes no requirements.

注意:强调我的。

关于c - 未初始化的变量的值是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58168645/

相关文章:

c - C中的while循环格式

c++ - QT ntp 并消除差异

c - 连接共享内存段时出错

C - 将未初始化的变量传递给数组元素

c++ - 尝试写入二进制文件时出现垃圾

Char x[50] 和 Char x[100] 输出

java - 当对象尚未初始化时如何跳过 while() 循环的条件?

c# - 从 C# 中的构造函数调用实例方法

javascript - 对于 Javascript 游戏引擎,重新使用全局变量比制作本地变量更有效还是更不有效?

C:读入整数数组的垃圾值