我有几个关于可变数量参数的问题:
为什么
va_start
、va_arg
和va_end
定义为宏而不是函数?va_start
是如何工作的?它是否有权访问函数调用堆栈并遍历堆栈直到找到最后指定的参数?
最佳答案
Rationale for International Standard—Programming Languages—C 中介绍了为什么它们是宏的基本原理。在 7.15
Variable arguments 部分说:
va_start and va_arg must exist as macros, since va_start uses an argument that is passed by name and va_arg uses an argument which is the name of a data type.
本文How Variable Argument Lists Work in C更详细地介绍了原因并给出了可能的 x86 实现:
typedef char *va_list;
#define va_start( list, param ) (list = (va_list)(¶m + sizeof( param )))
#define va_arg( list, type ) (*(type *)((list += sizeof( type )) - sizeof( type ))
在 C++ 中,您有很多其他选择,并且 Variable number of arguments in C++?可能涵盖了所有这些。
关于c++ - 可变数量的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20204671/