用C未初始化的变量 [英] Uninitialized variable in C

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

问题描述

我是一个有点困惑。据我所知,如果你声明用C一个int,没有初始化它,为例如: INT X;

I'm a little bit confused. As far as I know, if you declare an int in C, without initializing it, for e.g: int x;

所以它的价值是不确定的。因此,如果我们尝试使用它还是应该有未定义的行为。

so its value is indeterminate. So if we try to use it or should have undefined behavior.

所以,如果我运行下面的code在VS2010这程序崩溃。

So if i'm running the following code in VS2010 It crash the program.

int main(){
    int a;
    printf("%d\n",a);
    return 0;
}

现在让我们来看看下一个code,它不提供任何警告和不会崩溃(为什么?)

Now lets take a look at the next code, which does not provide any warning and does not crash (why?)

void foo(int *var_handle){
    // do nothing
}

int main(){
    int a;
    foo(&a);
    printf("%d\n",a); // works, prints some big value
    return 0;
}

你能解释一下这个行为?我们只加入到什么事情都不做一个函数的调用,但现在不会编程崩溃。

Can you explain the behavior of this? we only added a call to a function which does nothing at all, but now program wont crash.

推荐答案

读取未初始化变量的值导致不确定的行为。和未定义行为意味着它的可以崩溃。这并不意味着它的有义务崩溃。

Reading the value of an uninitialized variable leads to undefined behavior. And undefined behavior means that it can crash. It doesn't mean it will or it is obliged to crash.

这是未初始化的变量有不确定的价值 - 它只是未知它的价值是什么。因此,在实践中,有任何理智的实施,这种code将presumably永不死机。有一个有效的内存地址备份变量,它有一些垃圾内容,的printf()读它没有问题,除$ P $点作为一个整数,打印出来,这是所有

An uninitialized variable has unspecified value - it's just unknown what its value is. So in practice, with any sane implementation, this kind of code will presumably never crash. There's a valid memory address backing the variable, it has some garbage content, printf() reads it without problem, interprets it as an integer and prints it, that's all.

这篇关于用C未初始化的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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