I am trying to understand how generally returning from function works at machine level in C. From Microsoft’s documentation and many other resources define returning from a function like this:
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.
But I could find none that gave a detailed explanation on the execution of return statements. I watched a Youtube video (it was the only one which i could find that discussed this at machine level).
Let’s say i have a simple code:
int square(int i){
int val = i*i;
return val;
}
int main(){
int num = square(7);
return 0;
}
How will the execution look at machine level in general for the above code? I don’t want to go in the details on the types of registers and instruction call that will be used but an over the top working which can be applied to all architectures, if possible.
From what I could learn through the video and searching over the internet. I think it should go like this.
-
An integer variable num is created on stack.
-
The function square() is executed with 7 as its argument and for that following steps will occur.
- A stack frame is created on the stack for the square() functions and the argument 7 gets copied and stored in this stack frame.
- Stack pointer moves to the stack frame of the function.
- Executes everything
- The result of multiplication has to be returned so the CPU will store it somewhere (this should vary depending on the compiler used, right?)
- The stack frame created for the function gets cleaned up.
- The stack pointer now moves back to the caller.
-
The returned value gets copied in num
Is this how in general the CPU will do the execution for code 1?
Divyansh Singh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
5