为什么在返回未初始化的变量时编译器不报错? [英] Why doesn't the compiler give an error when an uninitialized variable is returned?
问题描述
#include <iostream>
using namespace std;
int weirdVariable = weirdVariable + 1;
int main() {
cout<< weirdVariable ;
return weirdVariable ;
}
我只是想知道这个未初始化的变量如何不返回错误并返回 1.所以我的问题是,它如何/为什么返回值1".这个程序在逻辑上有效吗?还是有什么缺陷?
I was just wondering how this un-initialized variable is not returning error and returning 1.So my question is, how/why is it returning the value "1". Is this program logically valid? Or is it some flaw?
推荐答案
并非未初始化.具有静态存储持续时间的变量(如全局变量)在任何进一步初始化之前首先进行零初始化.所以 weirdVariable
以值 1 结束.
It's not uninitialized. Variables with static storage duration (like a global variable) are first zero-initialized before any further initialization. So weirdVariable
ends up with the value 1.
§3.6.2 [basic.start.init] 具有静态存储持续时间 (3.7.1) 或线程存储持续时间 (3.7.2) 的变量应在任何之前进行零初始化 (8.5)其他初始化发生.
§3.6.2 [basic.start.init] Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place.
如果您将 wierdVariable
声明为 main
的局部变量,它将是未初始化的.这会给您带来未定义的行为,因为在未初始化的对象上执行左值到右值的转换(读取:使用的值)会产生未定义的行为.
If you were to declare wierdVariable
as local to main
, it would be uninitialized. This will give you undefined behaviour because performing lvalue-to-rvalue conversion (read: using the value of) on an uninitialized object gives undefined behaviour.
§4.1 [conv.lval] 如果泛左值所指的对象 [...] 未初始化,则程序需要进行此转换的行为具有未定义的行为.
§4.1 [conv.lval] If the object to which the glvalue refers is [...] uninitialized, a program that necessitates this conversion has undefined behavior.
这篇关于为什么在返回未初始化的变量时编译器不报错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!