Reputation:
#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 ?
Upvotes: 3
Views: 724
Reputation: 91119
This is because ip
keeps the value it has, even if the variable it points to went out of existence.
You should take extremely care doing this, because in a constellation like
#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);
}
{
float j=400.0;
}
//printf("i=%d\n", i); /* Now this will cause an error, i has Block scope, fair enough */
printf("*ip=%d\n", *ip);
return 0;
}
the variables i
and j
might share their location as they never coexist. If ip
points there, j
's value might become corrupted.
Upvotes: 0
Reputation: 60691
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.
Upvotes: 2