C 编译器如何实现具有可变数量参数的函数? [英] How does the C compiler implement functions with Variable numbers of arguments?

查看:30
本文介绍了C 编译器如何实现具有可变数量参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前几天我参加了一个技术面试,被问到C 编译器如何实现具有可变数量参数的函数?它是如何通过栈上的?

I attended a technical interview a few days ago, and I was asked How does the C compiler implments function with Variable number of arguments? How does it pass the on the stack?

有谁知道或者可以解释一下吗?

Does anyone know or can explian that?

谢谢,丹

推荐答案

据我所知,用 C...

As far as I know, with C...

  • 调用函数按从右到左的顺序将参数压入堆栈.

  • the caller function pushes arguments onto the stack in right-to-left order.

调用者负责在被调用函数执行后从堆栈中删除参数.这可能正是因为调用者被保证知道它在堆栈上放了多少参数,而被调用的函数可能会出错.

the caller is responsible for removing the arguments from the stack after the called function has executed. This is probably precisely because the caller is guaranteed to know how many arguments it put on the stack, while the called function might get it wrong.

P.S.: 调用约定通常是特定于实现的.我刚刚描述的称为cdecl"调用约定.将此与通常称为stdcall"的调用约定进行对比,其中被调用函数负责从堆栈中删除其参数.因此,它不支持变长参数列表.

P.S.: Calling conventions are usually implementation-specific. What I just described is known as the "cdecl" calling convention. Contrast this to a calling convention generally known as "stdcall", where the called function is responsible for removing its arguments from the stack. Because of that, it does not support variable-length argument lists.

P.P.S.:正如用户 nategoose 评论的那样,我没有提到变量参数列表实际上是如何使用的.参见例如POSIX 文档 <stdarg.h> 标题 了解更多信息.

P.P.S.: As user nategoose commented, I didn't mention how variable argument lists are actually used. See e.g. the POSIX documentation for the <stdarg.h> header for more information.

这篇关于C 编译器如何实现具有可变数量参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆