用C局部变量为什么默认值是一样的吗? [英] Why default value of local variables in C is same?

查看:146
本文介绍了用C局部变量为什么默认值是一样的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>  
int main()
{
    int i,j=3;
    i=4+2*j/i-1;
    printf("%d",i);
    return 0;
}

这将打印9每一次,虽然我没有初始化,
所以,
它必须打印任何垃圾值。
请解释...

It will print 9 every time,though i is not initialized, So, it must print any garbage value. Please Explain...

推荐答案

未初始化的局部变量的C语言中的价值是不确定的,阅读它可以调用未定义的行为。

The value of an uninitialized local variable in C is indeterminate and reading it can invoke undefined behavior.

现在,重复执行的某个特定的程序的编译的特定的编译器的中的一个特定的环境的(因为你正在做的)可能产生相同的(还是不确定的过程中,)的行为。这可能是因为操作系统会在每次运行它​​,因此你的程序读取垃圾有被每次都在同一个很好的机会(但它仍然是垃圾,不过)时间通常给你的流程范围相同的逻辑内存。或者它可能是因为编译器甚至懒得给你,你会读出垃圾的二进制重新presentation,而是给你别的东西(只要它不违反标准)。

Now, repeatedly executing a particular program compiled with a particular compiler in a particular environment (as you are doing) is likely to yield the same (still undefined, of course) behavior. This could be because the OS will usually give your process the same range of logical memory every time you run it and thus the garbage that your program reads has a good chance of being the same every time (but it's still garbage, nonetheless). Or it could be because the compiler doesn't even bother to give you a binary representation of the garbage you would be reading and instead gives you something else (as long as it doesn't violate the standard).

这篇关于用C局部变量为什么默认值是一样的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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