[英]What happens in C when you print a declared, but unassigned variable?
Why does the following snippet cause random numbers to print to the screen with printf
, but putchar
always outputs 1? 为什么以下代码段会导致使用printf
将随机数打印到屏幕上,而putchar
始终输出1?
#include <stdio.h>
int main() {
char c;
printf("%d\n", c );
putchar(c);
}
According to C99 standard, this is undefined behavior . 根据C99标准,这是未定义的行为 。 Let's see why: 让我们看看为什么:
Section 6.7.8.9 says that 6.7.8.9节说
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. 如果未自动初始化具有自动存储期限的对象,则其值不确定。
This applies to your variable c
, because it has automatic storage duration, and it is not initialized explicitly. 这适用于您的变量c
,因为它具有自动存储持续时间,并且未显式初始化。
Section J.2 says that J.2节说
The behavior is undefined in the following circumstances: 在以下情况下,行为是不确定的:
... ...
The value of an object with automatic storage duration is used while it is indeterminate 具有自动存储持续时间的对象的值在不确定时使用
This applies to your code as well, because you read c
when you pass it as a parameter to both printf
and putchar
, and the value of c
is still indeterminate, because it has not been assigned. 这也适用于您的代码,因为在将c
作为参数传递给printf
和putchar
时读取了c
,并且c
的值仍然不确定,因为尚未分配它。
1) The c variable first has a random value(default/garbage value) to itself as you declared-but-did-not-initialize your char c to any defined letter or value of ur interest(character). 1)当您声明但未将字符c初始化为您定义的任何感兴趣的字母或值(字符)时,c变量首先对其自身具有随机值(默认值/垃圾值)。
2) Next you tried to printf the %d(digit/decimal/numerical value) of the char c, so now it is giving you a converted value of the garbage which was earlier assigned to c when you declared the char c in the first place. 2)接下来,您尝试打印出char c的%d(数字/小数/数值),因此现在它为您提供了垃圾的转换值,该垃圾早在您在第一个中声明char c时便已分配给c了。地点。
3) Finally you tried to use putchar(c), which again behaves similarly because your char c is uninitialized and is still being read thereby re-trying to manage with an undetermined value to be printed onto the screen. 3)最后,您尝试使用putchar(c),由于您的char c尚未初始化并且仍在读取中,因此再次具有类似的行为,从而尝试使用不确定的值进行管理以打印到屏幕上。 (since the same un-initialized character variable c is being passed to both kind of printing as a parameter). (因为将相同的未初始化字符变量c作为参数传递给两种打印)。
Yes these 3 statements are a bit clumsy to understand but they are as layman as it can get to help speed-up some understanding regarding this query of yours. 是的,要理解这3条语句有些笨拙,但它们都是外行,因为它可以帮助加快对您查询的理解。
Pay attention to the 1st comment response to your question by @bluemoon. 注意@bluemoon对您的问题的第一条评论回复。 Those 3 words alone litterally have a huge amount of sensibility and meaningfull-ness to them, to a point that it also tells you what you have done erroneous in your own code(your actions)."UNDEFINED"(try relating the same with UNINITIALIZED). 仅这三个词就对它们具有极大的敏感性和意义,以至于它还告诉您您在自己的代码中所做的错误(您的操作)。 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.