0
int testFun(int A)
{
   return A+1;
}
int main()
{
   int x=0;
   int y= testFun(x)
   cout<<y;
}

As we know, the stack saves the local variables, which means when I was in the main function, the stack had variables (x and y) and when I called the function (testFun) the stack had the variable(A) and when I return from (testFun) The stack pops the last frame But the quesion here, when I return from (testFun), how it know the last place it were in the main function before calling the (testFun)

trincot
  • 317,000
  • 35
  • 244
  • 286
  • There is an [*activation record*](https://stackoverflow.com/questions/1266233/what-is-activation-record-in-the-context-of-c-and-c) involved. Local variables and arguments aren't the only thing considered. – WhozCraig Oct 06 '19 at 02:22

1 Answers1

3

when I return from (testFun), how it know the last place it were in the main function before calling the (testFun)

The compiler parses the code and generates machine instructions that run on the CPU. A function call produces a CALL instruction. When the function exits, a RET instruction is used to return to the caller.

The CALL instruction pushes the address of the instruction that follows the CALL itself onto the call stack, then jumps to the starting address of the specified function.

The RET instruction pops that address from the call stack, then jumps to the specified address.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770