-1

My question is that when the lifetime of a local variable is at block level then why the pointer is still printing the value of a local variable even outside the block

 #include<iostream>

  using namespace std;

int main(){

    int *p;
    {
        int n;
        n=5;
        p=&n;
    } 
    cout<<*p;
    return 0;
}
Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50
Nadeem Bhati
  • 739
  • 1
  • 8
  • 13

1 Answers1

1

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.

P.P
  • 117,907
  • 20
  • 175
  • 238