未初始化变量的值是多少? [英] What will be the value of uninitialized variable?
问题描述
可能重复:
是否明确指定了未初始化的数据行为?
我尝试了以下代码
#include<stdio.h>
void main()
{
int i;
printf('%d',i);
}
结果在 VC++ 中给出了垃圾值,而在 tc 中同样为零.正确的值是多少?默认情况下,未初始化的变量的值是否为零?还是会包含垃圾值?
The result gave garbage value in VC++, while same in tc was zero. What will be the correct value? Will an uninitialized variable by default have value of zero? or it will contain garbage value?
接下来是一样的
#include<stdio.h>
void main()
{
int i,j,num;
j=(num>0?0:num*num);
printf("
%d",j);
}
上面代码的输出是什么?
What will be the output of the code above?
推荐答案
从技术上讲,未初始化的非静态局部变量的值是Indeterminate[Ref 1].
简而言之,它可以是任何东西.访问此类未初始化的变量会导致未定义行为.[Ref 2]
Technically, the value of an uninitialized non static local variable is Indeterminate[Ref 1].
In short it can be anything. Accessing such a uninitialized variable leads to an Undefined Behavior.[Ref 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 节未定义的行为:
在使用不可移植或错误程序结构、错误数据或不确定值对象时的行为,本国际标准对此没有任何要求.p>
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.
注意:强调我的.
这篇关于未初始化变量的值是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!