#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 i is out of scope, so cannot be accessed, but by chance its memory location on the stack, stored in ip, has not been overwritten. You absolutely cannot rely on this behaviour, but in practice you'll find it holds true on many platforms.
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