Confusion in Scope and Life Time of a local variable in c/c++ -
this question has answer here:
my question when lifetime of local variable @ block level why pointer still printing value of local variable outside block
#include<iostream> using namespace std; int main(){ int *p; { int n; n=5; p=&n; } cout<<*p; return 0; }
scope refers the availability of identifier.
life time refers actual duration object alive , accessible legally during execution of program. distinct things.
your code has undefined behaviour because lifetime of object n on @ closing } because access through pointer.
a simple example might make clearer:
#include<stdio.h> int *func() { static int var = 42; return &r; } int main(void) { int *p = func(); *p = 75; // valid. } here, var has static storage duration. i.e. it's alive until program termination. however, scope of variable var limited function func(). var can accessed outside func() through pointer. valid.
compare program. n has automatic storage duration , lifetime , scope both limited enclosing brackets { }. it's invalid access n using pointer.
however, if make change (n) storage class static can object alive outside enclosing brackets.
Comments
Post a Comment