#include<stdio.h>
void bar()
{
int a=4;
}
void foo()
{
int a;
printf("%d",a);
}
int main()
{
bar();
foo();
}
I'm sure that the above program gives the output as some junk value(Thats what happenes when i compile and run). But I read in an article that it is possible for some compilers to give the output as 4 itself. The explanation given was that it is related to activation stack and activation frames. I dont understand. Is it something like the value of int a=4 from bar() function is stored somewhere in the activation stack for future use??I'm confused!!
To be clear it is possible that foo's a will end up with the 4 in it that bar set there (nothing to do with them having the same name BTW). But this is highly dependent on the compiler machines etc.
What you are actually doing (in foo) is 'undefined behavior', you use a without giving it a value. Undefined means the compiler may do anything, format your harddrive, print any random value including you best friends birthdate, or it could print 4.
Why might it be 4, because the way stack frames are built on many systems will results in bar writing 4 to an address and foo reading it back. The 2 functions have the same paramters, return type and number of locals so its possible that the first local will be allocated in the same memory location. THis is why you read that they could have the same value, but this is by accident not by design
BTW did you get 4 or not, probaly not