6

Here and Here I found that variables in block are created when execution reaches that block,

To prove that I tried this:

 int main()
{

  {
      char a;
      printf("Address of a %d \n",&a);
  }

  char b;
  printf("Address of b %d \n",&b);

}

As expected b was created first (because outer block is executed sooner than inner), and when the execution reached inner block a was created. Output of the above code:

Address of a 2686766
Address of b 2686767

(Tested on x86 (stack grows downwards, so variable with greater address was created first)).

But what about this one?:

int main()
{

   {
       char a;
       printf("Address of a %d \n",&a);
   } // I expected that variable a should be destroyed here


   {
       char b;
       printf("Address of b %d \n",&b);
   }

}

Output:

Address of a 2686767
Address of b 2686766

I expected that a was destroyed at closing brace of the first block statement, so address where a was located is now top of stack, and b should be created here, thus in the Output above both addresses should be equal, but they aren't? Are variables destroyed at the end of block? If not, why?

Community
  • 1
  • 1
PcAF
  • 1,975
  • 12
  • 20

2 Answers2

10

There are no rules for how the compiler places variables in memory. It could very well reserve space for both of them at the same time, if that is "easier" in some way.

It is allowed to reuse the space for variables in different scopes, but not required. Saving a single byte might not be worth the trouble of trying to "optimize" the allocation.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
0

Destroying a variable in C++ means 'calling it's destructor'. Nothing more, nothing else. Since built-in types like chars have no destructors, destroying them is not visible for the observer.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • @NathanOliver, and where did I say otherwise? – SergeyA Mar 31 '16 at 13:49
  • @NathanOliver, do you have any proof for this? Assuming b is not a char but an object with side-effect constructors, when do you think that constructor would be executed? – SergeyA Mar 31 '16 at 13:53
  • 1
    @NathanOliver, I didn't know standard has a distinction there for trivial/non-trivial constructors. I will remove the last paragraph. – SergeyA Mar 31 '16 at 14:12