未初始化的变量会怎样? C ++ [英] What happens to uninitialized variables? C++

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

问题描述

int main()
{    
    int a;
    cout << a;
    return 0;
}

我想知道为什么输出值0。我以为如果变量未初始化,就会输出垃圾值。

I am wondering why the value 0 is being output. I thought if a variable is uninitialized, it would output a garbage value.

但是,我还记得整数的默认值为0,所以我有点

However, I also remember hearing that the default value of an integer is 0 so I am a bit confused.

谢谢

推荐答案

未初始化函数的默认行为C ++中的范围(即本地)整数是不确定,很好; 但是,如果在定义该值之前就使用了该值,则会引入未定义的行为,并且可能发生任何事情-恶魔可能会飞出你的鼻子

The default behavior of an uninitialized function scope (i.e., local) integer in C++ is for it to be indeterminate, which is fine; however if that value is used before it is defined it introduces undefined behavior, and anything could happen - demons could fly out of your nose.

此页面位于 cppreference 提供了默认整数行为的示例。

This page on cppreference provides examples of default integer behavior.

另一方面,所有非局部,线程局部变量(不仅仅是整数)都是 零初始化

On the other hand, all non-local, thread-local variables, not just integers, are zero initialized. But this case wasn't included in your original example.

(请注意:通常简单地初始化变量并完全避免潜在的危险通常被认为是一种好习惯。尤其是以全局变量的形式。)

(Side note: It is generally considered good practice to simply initialize variables anyway and avoid potential hazards altogether... Especially in the form of global variables. )

在罕见的特殊情况下(例如某些嵌入式系统),使用全局变量的最佳做法也有例外。会在启动时或在其初始循环迭代期间根据传感器读数来初始化值...并且需要在其循环范围结束后保留​​一个值。

There are exceptions to best practice using global variables in rare special cases, such as some embedded systems; which initialize values based off of sensor readings on startup, or during their initial loop iteration... And need to retain a value after the scope of their loop ends.

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

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