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?
This is typically implemented using a call stack:
The details are typically mandated by the hardware architecture for which the code is being compiled.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With