Ian Collins wrote:
somenath wrote:
>Hi All ,
I have one question regarding scope and lifetime of variable.
#include <stdio.h>
int main(int argc, char *argv[])
{
int *intp = NULL;
char *sptr = NULL;
{
int i =5;
char *s = "hello";
intp = &i;
sptr = s;
}
printf("value of i = %d\n",*intp);
printf("value of sptr = %s \n",sptr);
return 0;
}
Out put of the program
value of i = 5
value of sptr = hello
The variable i, and s has block scope .But as s points to string
literal life time of the s is through out the program .
My question is as i has only block scope so once it goes out of scope
address of i becoming meaning less. So is it guaranteed that first
printf statement will always print 5 ?
It prints whatever is at the location is points to contains. The result
is undefined if the pointer points to a variable that is out of scope.
No, that's not the problem. It is perfectly legal to
use a pointer to an out-of-scope variable, and in fact it
is quite usual to do so. "Scope" refers to the visibility
of the variable's identifier, not to the variable's existence.
The undefined behavior arises when the pointed-to variable's
lifetime ("storage duration") has ended. In somenath's example
this occurs at the same point in the source where the identifier
goes out of scope, and the fact that the two things happen at
the same point seems to have led to some confusion about which
causes what. They are, however, distinct notions -- and since
the question was specifically about the two notions it is as
well to clear up whatever confusion arises.
--
Eric Sosman
es*****@ieee-dot-org.invalid