You seem to have misunderstood data lifetime in C++. When local data is declared in a scope block (whether in a function, loop, or other control structure), it remains on the stack until that scope block ends.
That means the entirety of arr1
remains allocated and on the stack until main()
finishes, no matter what else you do. It will not be overwritten by subsequent local variables in the same function, or variables nested in deeper scope blocks.
In your second loop, variable a
is (theoretically) being created and destroyed on every iteration of the loop body. That means you don't have 500 instances of a
on the stack during the loop -- you only ever have one. (In practice, the compiler almost certainly optimises that out though, since it's not doing anything useful.)