C 中未初始化变量的行为 [英] Behaviour of Uninitialized Variables in C

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

问题描述

我有一个关于未初始化变量如何在 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:

6.2.4

The initial value of the object is indeterminate.

This is further described in

6.7.9

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

The definition of "indeterminate" says

3.19.2

indeterminate value

either an unspecified value or a trap representation

And finally

J.2 Undefined behavior

The behavior is undefined in the following circumstances:

...

The value of an object with automatic storage duration is used while it is indeterminate (6.2.4, 6.7.9, 6.8).

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 中未初始化变量的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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