gpt4 book ai didi

c++ - 可变数量的参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:02:57 24 4
gpt4 key购买 nike

我有几个关于可变数量参数的问题:

  1. 为什么 va_startva_argva_end 定义为宏而不是函数?

  2. 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)(&param + 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com