INTERESTING

#include<iostream>
using namespace std;

int main()
{
int x;
{
int x=4
}
cout<<x;
system("pause");
return 0;

}// this program outputs default value

but in this case

#include<iostream>
using namespace std;

int main()
{

{
int x=4
}
int x;
cout<<x;
system("pause");
return 0;

}//this programme outputs x=4 but not default value.what is difference in these two programmes
When you do not initialize a variable in the local/automatic memory scope, a variable created/allocated in the memory gives a value whatever it holds currently, which may be junk or LAST VALUE.

In the first program, the first x is created in main scope and the second x is created and destroyed within the sub scope itself. Since you did not initialize/change value for the first one, it remained same, whatever it was, junk, default, etc etc.

In the second program, you are creating a variable called x after the same amount of memory was created and destroyed for a similar data type (meaning, same amount of memory). Hence it picked up last accessed (and destroyed) memory and allocated same for second x in the main scope. And you did not initialize it, so it shows whatever it held for the earlier and still there in the uninitialized memory.
C++ does not guarantee what value it would hold if not initialized, it may be last held or any other junk lying there.


Good luck :)
Topic archived. No new replies allowed.