I’m playing with c++ in VisualStudio2010
Please explain why IT happens:
int a, b;
int *p, *q;
cout << a << " " << b;
prints out “0 0”. Well it’s understandable, uninitialized integer should be 0;
but
int a, b;
int *p, *q;
p = &a;
cout << a << " " << b;
output is “1792816880 0”
So if I assign pointer to uninitialized variable it change value from default.
Why?
Edit clarification: the question was not about value of uninitialized variable
int a; int *p;
cout << a; // would be 0, because it's loacal variable
p = &a;
cout << a; //not 0;
How getting pointer of a could change it value?
when we init variable, we allocate space, some bits, they could be anything, but “p = &a” does it actually change bits in this space?
No.
There is no guarantee of that, it depends on the storage class, If your int is local variable it has a auto storage and it need not be 0.
Accessing Unitialized variables causes Undefined Behavior and Your code is causing an Undefined Behavior. Once there is an Undefined Behavior all bets are off and the behavior cannot be explained.
Regarding Undefined Behavior,
C++ Standard section 1.3.24 states:
EDIT:
Given the above that this is Undefined Behavior and One should not write any code which relies on such behaviors, infact One should not even think of writing such code. I find it irrelevant & unproductive to dig in to the implementations of all those compilers to seek an explanation of why it works this way.
If someone finds this reply hardheaded, You are free to downvote. If the downvote count exceeds the upvotes, I would know the answer is unwelcome and I will delete it.