Genarto Genarto - 9 months ago 76
C++ Question

What happens to the variables inside?

What happens to the variables inside that function ?

void function()
int a = 5;
a += a; //a contain 10

int main()
return 0;

so what happened here after the function (function()) execution is done does this variable (a) is it still found in memory (uses memory) with its last value which is (10) or its destroyed completely and no longer in memory ?

Answer Source

It's not really specified. I'll describe the naive case first, and then explain why it may not really apply.

Naively, the memory a was stored in still exists, although the name a is no longer reachable outside function. The memory may or may not still contain 10 - the compiler is free to overwrite it or to not bother. Obviously it may also be reused as something else any time afterwards.

If a was really allocated in memory, that might be in a region known as the (call) stack, but this is just a popular calling convention and not required by the language.

Now, the compiler is also free to store a only in a register since it notices the address is never taken, in which case it was never in memory in the traditional sense.

The compiler is further free to notice that a is never observably used at all, and not bother emitting any of the code inside function.