[英]How are parameters passed on the stack in variable argument function?
I thought that the function removes the parameters from the stack after it's done, but a function like printf removes a variable number of parameters from the stack when it's called. 我以为函数完成后会从堆栈中删除参数,但是像printf这样的函数在调用时会从堆栈中删除可变数量的参数。
How does it know how many parameters to remove from the stack? 它如何知道要从堆栈中删除多少个参数? Is there a secret argument to specify how many arguments are passed?
是否有一个秘密参数指定要传递多少个参数?
Thanks 谢谢
The C calling convention specifies that is the caller and not the callee the one responsible from popping the parameters from the stack. C调用约定指定是调用者,而不是被调用 者 ,这是从堆栈中弹出参数的原因。 That's why functions with a variable argument list must be
cdecl
. 这就是带有可变参数列表的函数必须为
cdecl
。 So, 所以,
I thought that the function removes the parameters from the stack after it's done.
我认为该函数完成后会从堆栈中删除参数。
That's only true for certain calling conventions, it isn't true for the C calling convention . 这仅适用于某些调用约定,不适用于C调用约定 。
How does it know how many parameters to remove from the stack?
它如何知道要从堆栈中删除多少个参数? Is there a secret argument to specify how many arguments are passed?
是否有一个秘密参数指定要传递多少个参数?
It doesn't, and no there is no secret argument. 否,没有,没有秘密的论点。
The caller function will clean the stack (in the correct calling convention). 调用者函数将清理堆栈(按照正确的调用约定)。 The compiler will generate the code for that.
编译器将为此生成代码。 The compiler is the one knowing exactly how many arguments you passed on the arguments list, because, well, it compiled it..
编译器是一个确切知道您在参数列表上传递了多少个参数的编译器,因为它编译了它。
The calling code cleans up the stack, and it's up to the called function to correctly determine that there is "enough" arguments have been passed for whatever it wants to do. 调用代码将清理堆栈,并由被调用函数正确确定是否有“足够”的参数已传递给它想要执行的操作。 This doesn't have to be an argument as such, it could be something like this:
这不必一定是这样的参数,它可以是这样的:
int sum(int first, ...)
{
int s = first;
int v;
va_list va;
va_start(va, first);
while (v = va_arg(va, int) != -1)
{
sum += v;
}
va_end(va);
return sum;
}
x = sum(1, 2, 3, -1);
y = sum(1, 2, 3, 4, 5, 6, 7, 8, 9, -1);
Link to how many arguments in varargs function 链接到varargs函数中的多少个参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.