如果C中的语句和垃圾值 [英] if statment and garbage value in C

查看:51
本文介绍了如果C中的语句和垃圾值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C编程的新手.我知道这是一个非常简单的问题,但我需要一些建议. 我正在使用控制结构if statement进行锻炼.我遇到了一个例子

I am newbie to the C programming.I know this is a very simple question but I need some advice. I am exercising with the control structure if statement. I came across one example

这是代码:-

#include<stdio.h>
int main()
{
    int a = 200, b, c ;
    if (a >= 300)
    {
        b = 100 ;
        c = 200 ;
    }
    printf ( "b=%d\nc=%d", b, c ) ;
    return 0;
} 

其输出为:-

b=32767
c=0

在这里,我期望两个值的输出均为零.通过查看此输出,我对为什么变量b中的垃圾值感到惊讶.

Here i am expecting the output as the both value to be zero. By seeing this output i am little surprised that why the garbage value in the variable b.

其背后的原因是什么?还是我以错误的方式声明了变量.这背后的整个场景应该是什么?

What is the reason behind that?Or I am declaring the variable in wrong way. what should the whole scenario behind this?

推荐答案

万一

if (a >= 300)

失败,bc将不会被分配任何值.

fails, b and c will not be assigned any values.

现在,bc是自动局部变量,除非显式初始化,否则它们将包含不确定的值.

Now, b and c being automatic local variables, unless initialized explicitly, they contain indeterminate values.

请参阅C11,第§6.7.9章,初始化

Referring C11, chapter §6.7.9, Initialization

如果未自动初始化具有自动存储期限的对象,则其值为 不确定.[...]

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

使用统一的局部变量访问其值会调用未定义的行为.

Using unitialized local variables to access their values invoke undefined behavior.

对于未定义行为

使用具有自动存储持续时间的对象的值 不确定.

The value of an object with automatic storage duration is used while it is indeterminate.

因此,始终建议您初始化局部变量,例如

So, it's always advisable to initialize your local variables, like

int a = 200, b = 0, c = 0;

也就是说,FWIW int main()应该至少是int main(void)符合标准.

That said, FWIW, int main() should be int main(void) at least to conform to the standard.

这篇关于如果C中的语句和垃圾值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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