user12976036
user12976036

Reputation:

How are values returned from a function using the stack?

Assume this code:

int add(int a, int b){
    int c = a+b;
    return c;
}

int main(){
  printf("%d\n", add(3,4));
}

The following is usually how this is implemented in assembly:

  1. push 4 to stack
  2. push 3 to stack
  3. push return address which is the address of the next instruction, print() to stack
  4. call add
  5. do addition and push c on the stack
  6. pop c from stack (?)
  7. return to main

So what happens to the return value? It can't be on the add frame as that will be cleared at the end. Does it get put onto the stack of main?

Let's assume the values are pushed to the stack and not to a register.

Upvotes: 4

Views: 1925

Answers (1)

Govind Parmar
Govind Parmar

Reputation: 21532

It depends on the architecture and calling convention. In x86-32 just about every calling convention has the return value in eax or edx:eax for 64-bit results. So your add function might have the instructions:

mov eax, dword ptr [esp+4] ; put 1st arg in eax
add eax, dword ptr [esp+8] ; add eax with 2nd arg
ret                        ; return

No extra work is needed since the return value is already supposed to be in eax.

That said you aren't going to find a "general case" answer for this unless you are asking about a specific architecture, and even then, there can be multiple different calling conventions on it.

Upvotes: 3

Related Questions