问题描述
我有一个关于未初始化变量如何在 C 中工作的问题.如果我声明一个变量然后打印它,程序应该打印一个随机值,但是我的程序几乎总是输出 0.如果我尝试声明第二个变量,程序总是输出 16 作为新分配的值.
#include int main(){int x,y,z,t;printf("%d %d",x,y);}
该程序输出 0 和 16,但是如果我添加以下代码行:y--;
在声明变量之后但在打印它们之前,程序输出 x=15 和 y =-1,与我之前拥有的完全不同的值.为什么会发生这种情况?C 如何处理未初始化的变量?
根据标准(草案 N1570),以下内容适用:
6.2.4
对象的初始值是不确定的.
这在
中进一步描述6.7.9
如果没有显式初始化具有自动存储期的对象,则其值为不确定.
不确定"的定义说
3.19.2
不确定值
未指定的值或陷阱表示
最后
J.2 未定义行为
在以下情况下行为未定义:
...
具有自动存储期的对象的值被使用时不确定 (6.2.4, 6.7.9, 6.8).
综上所述:在读取未初始化的变量时无法知道您得到了什么值,而且甚至不确定您的程序是否会继续执行,因为它可能是一个陷阱.
I have a question regarding how uninitialized variables work in C. If I declare a variable and then print it, the program should print a random value, however my program almost always outputs 0. If I try to declare a second variable, the program always outputs 16 as the new assigned value.
#include <stdio.h>
int main(){
int x,y,z,t;
printf("%d %d",x,y);
}
This program outputs 0 and 16, however if I add the following line of code: y--;
right after declaring the variables but before printing them, the program outputs x=15 and y =-1, totally different values from what I had before. Why does this happen? How does C handle uninitialized variables?
According to the standard (draft N1570) the following applies:
This is further described in
The definition of "indeterminate" says
And finally
So all together: There is no way to know what value you get when reading an uninitialized variable and further it's not even sure that your program will continue to execute as it may be a trap.
这篇关于C 中未初始化变量的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!