Why doesn't the compiler give an error when an uninitialized variable is returned?

懵懂的女人 提交于 2020-01-01 05:46:08

问题


#include <iostream>

using namespace std;

int weirdVariable = weirdVariable  + 1;
int main() {
  cout<< weirdVariable ;
  return weirdVariable ;
}

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?


回答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] 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.

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] If the object to which the glvalue refers is [...] uninitialized, a program that necessitates this conversion has undefined behavior.




回答2:


Static and global variables are initialized to 0 by default so it's perfectly normal

The C standard ISO/IEC 9899:1999 a.k.a. C99 (and C++) standards say this must be so. See item 10 in section 6.7.8 ("Initialization") of WG14 N1256 for the exact text (https://stackoverflow.com/a/1294780/1938163)

By the way: it is good practice to initialize static variables, also just to render the code more readable!

static int myvar = 0;

Another drawback of not initializing them: if a compiler doesn't follow the standard, you might get in trouble

With regard to local variables that are both NOT static and NOT global, well, you might skip their initialization but that would yield undefined behavior. Don't really rely on it.



来源:https://stackoverflow.com/questions/21328655/why-doesnt-the-compiler-give-an-error-when-an-uninitialized-variable-is-returne

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!