#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?
So using an uninitialized variable will result in undefined behavior. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output.
An uninitialized variable is a variable that has not been given a value by the program (generally through initialization or assignment). Using the value stored in an uninitialized variable will result in undefined behavior.
In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software.
Local Variables If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error. Save this answer.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With