Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the compiler know where control should return to after a function call?

Tags:

c++

Consider the following functions:

int main()
{
    //statement(s);
    func1();
    //statement(s);
}

void func1()
{
    //statement(s);
    func2();
    //statement(s);
}

void func2()
{
    //statement(s);
}

How does the compiler know where to return to after the func2 has performed all its operations? I know the control transfers to function func1 (and exactly which statement), but how does the compiler knows it? What tells the compiler where to return to?

like image 563
Abbas Avatar asked Mar 07 '13 14:03

Abbas


2 Answers

This is typically implemented using a call stack:

  • When control is being transfered to a function, the address to return to is pushed onto the stack.
  • When the function finishes, the address is popped off the stack and used to transfer control back to the callee.

The details are typically mandated by the hardware architecture for which the code is being compiled.

like image 65
NPE Avatar answered Oct 25 '22 01:10

NPE


Actually, the compiler doesn't run the code, but the machine does, and when it calls a new function, it stores the address of the next instruction to be executed after the function currently being called on the stack, so that when the function returns it can pop it off back in to the Instruction Pointer (IP) and resume from there.

I've simplified things a bit for the sake of explanation.

like image 44
Tony The Lion Avatar answered Oct 24 '22 23:10

Tony The Lion