问题
#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