Scope refers to the the availability of an identifier.
Life time refers to the actual duration an object is alive and accessible legally during the execution of the program. They are distinct things.
Your code has undefined behaviour because the lifetime of the object n
is over at the closing }
because you access it through a pointer.
A simple example might make it clearer:
#include<stdio.h>
int *func()
{
static int var = 42;
return &r;
}
int main(void)
{
int *p = func();
*p = 75; // This is valid.
}
Here, var
is has static
storage duration. i.e. it's alive until the program termination. However, the scope of the variable var
is limited to the function func()
. But var
can be accessed even outside func()
through a pointer. This is perfectly valid.
Compare this to your program. n
has automatic storage duration and its lifetime and scope both are limited to the enclosing brackets { }
. So it's invalid to access n
using a pointer.
However, if you make change its (n
) storage class to static
then you can do what you do as the object is alive even outside enclosing brackets.