假设此代码:
int add(int a, int b){
int c = a+b;
return c;
}
int main(){
printf("%d\n", add(3,4));
}
以下通常是在汇编中的实现方式:
- push 4 to stack
- push 3 to stack
- push return address which is the address of the next instruction, `print()` to stack
- call add
- do addition and push c on the stack
- pop c from stack ??
- return to main
所以返回值发生了什么,它不能在add
帧上,因为它将在最后清除。它是否放入main
的堆栈中?
让我们假设这些值是按钉书钉而不是寄存器。
这取决于体系结构和调用约定。在x86-32中,几乎所有调用约定在64位结果中的返回值都在eax
或edx:eax
中。因此,您的add
函数可能具有以下说明:
mov eax, dword ptr [esp+4] ; put 1st arg in eax
add eax, dword ptr [esp+8] ; add eax with 2nd arg
ret ; return
由于返回值已经在eax
中,因此不需要额外的工作。
那就是说,除非您询问特定的体系结构,否则您将不会找到“一般情况”的答案,即使那样,它上可能会有多种不同的调用约定。