我写了这段代码:
#include<stdio.h>
int valFunc(int val){
return val;
}
int main(){
int a = 5;
int b = 7;
printf("%d",valFunc(a)+valFunc(b));
return 0;
}
里面的printf()的函数main()中,后valFunc(一)被调用和返回值5,在哪里呢main函数调用保存在此之前值5 valFunc(B) ?
我知道,如果该函数的编写方式如下所示,那么它将把函数valFunc(5)和valFunc(7)的返回值分别保存在整数变量a和b中。:
#include<stdio.h>
int valFunc(int val){
return val;
}
int main(){
int a = valFunc(5);
int b = valFunc(7);
printf("%d",a+b);
return 0;
}
但是在以前的代码中,我无法理解该函数将返回值保存在哪里?它会创建隐式变量并使用它们来保存其进度,然后再调用其他函数吗?或者是否存在其他机制?请解释。
是否在调用其他函数之前创建任何临时变量以将这些值存储在运行时堆栈上?在我编写的第二个代码中,很明显,main()将把这些值存储在a和b中,并将它们放在运行时堆栈中。但是由于没有变量,main()将如何对第一个代码执行此操作?
它非常依赖于系统体系结构,但是在最一般的情况下,当在C中调用函数时,结果将在特定的寄存器中返回,并且始终保持相同。如果我们专注于Intel X32-64,则返回值将在寄存器eax中传递32位,在rax中传递64。在这种情况下,从IA32的编译器发出的代码将(或多或少):
lea eax, a //Get parameter address
mov eax, dword ptr [eax] //Get the value
push eax //pass parameter on stack
call valFunc //call function
mov ebx, eax //save result in register ebx
lea eax, ba //Get parameter address
mov eax, dword ptr [eax] //Get the value
push eax //pass parameter on stack
call valFunc //call function
add eax, ebx //sum the results
push eax //pass the sum as parameter on stack
lea eax, fmtstr //Get the address of the format string "%d"
push eax //push it onto the stack
call _printf
作为一种变体,结果可以保存在堆栈中(即在所有寄存器都在使用的情况下):
....
call valFunc //call function
push eax //save result on the stack
lea eax, ba //Get parameter address
mov eax, dword ptr [eax] //Get the value
push ebx //save ebx on the stack
mov ebx, eax //save result in register ebx
call valFunc //call function
add eax, ebx //sum the results
pop ebx //Restore register ebx from stack
push eax //pass the sum as parameter on stack
....
我希望这可以澄清这一点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句