#include <stdio.h>
int main(int argc, char * argv[])
{
int *ip;
printf("%d\n", *ip);
ip=NULL;
if (1)
{
int i=300;
printf("Inside If Block \n");
ip=&i;
printf("*ip=%d----------\n", *ip);
}
//printf("i=%d\n", i); /* Now this will cause an error, i has Block scope, fair enough */
printf("*ip=%d\n", *ip);
return 0;
}
How come the last printf() returns the correct value of i?
Is it because the memory location still holds the value, even if i went out of scope?
How does it work ?
The local variable
iis out of scope, so cannot be accessed, but by chance its memory location on the stack, stored inip, has not been overwritten. You absolutely cannot rely on this behaviour, but in practice you’ll find it holds true on many platforms.