0

What happens to the variables inside that function ?

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

int main()
{
   function();
   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 ?

Genarto
  • 3
  • 2

3 Answers3

2

It's generally stored on the stack, that is it's automatically allocated, and the memory for those automatica allocations gets recycled for each function call. Your compiler might decide that this variable is actually useless and ignore it completely since it's never used and doesn't impact any other parts of your code, so what might happen is: Nothing.

In C and C++ it's important to remember there's a huge difference between local variables, which are considered to be automatically-allocated and only survive as long as the function is executing, and dynamically-allocated via pointers and new which survive until they're either removed with delete or the program terminates.

tadman
  • 208,517
  • 23
  • 234
  • 262
2

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.

Useless
  • 64,155
  • 6
  • 88
  • 132
0

When function ends all its local variables essentially disappear (more precisely, they disappear when their block ends).

Talking about their "last value" remaining "in memory" is a rather pointless exercise since there's a possibility that their value has never been in memory in the first place. And even if it has, there's no guarantee that it is still there, or that that memory is still accessible in any sense.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765