简体   繁体   English

编译器对 C 中的变量参数列表使用了什么样的数据结构?

[英]What kind of data structure is used by the compiler for variable argument lists in C?

When dealing with variable argument lists in C, I was just curious to know which data structure might a compiler be using when storing the variable arguments in a list.在处理 C 中的变量参数列表时,我只是想知道编译器在将变量 arguments 存储在列表中时可能使用哪种数据结构。

  1. Is it an array of void pointers?它是一个空指针数组吗?
  2. Is it a linked list of void pointers?它是 void 指针的链表吗?
  3. or anything else?还是别的什么?

No structure.没有结构。 The calling code just puts the arguments on the stack, it's the vararg function's responsibity to decode them properly.调用代码只是将 arguments 放在堆栈上,正确解码它们是 vararg 函数的责任。

For example in case of printf, the first argument is fixed, a c string, and the rest is decoded based on what's in the string.例如,在 printf 的情况下,第一个参数是固定的,一个 c 字符串,rest 根据字符串中的内容进行解码。 C just gives you tools to access these elements so you don't have to do stack pointer arithmetic based on size of the fields (which is architecture dependent..) C 只是为您提供访问这些元素的工具,因此您不必根据字段的大小进行堆栈指针运算(这取决于体系结构..)

The compiler actually doesn't do anything special.编译器实际上并没有做任何特别的事情。 During compilation, when a function is invoked, the compiler will as usual generate code to push the entire list of the arguments onto the stack consecutively (often in reverse order, depends on the calling convention).在编译期间,当调用 function 时,编译器将照常生成代码以将 arguments 的整个列表连续推入堆栈(通常以相反的顺序,取决于调用约定)。

It is then the responsibility of the callee to detect and reference these arguments from the stack.然后被调用者负责从堆栈中检测和引用这些 arguments。 To do this the callee must know the number of arguments as well as the stack memory address of the first argument (this is always a known offset form the stack frame pointer).为此,被调用者必须知道 arguments 的编号以及第一个参数的堆栈 memory 地址(这始终是堆栈帧指针的已知偏移量)。 To determine the number of arguments, this information must be communicated.要确定 arguments 的数量,必须传达此信息。 This is often achieved in the following ways:这通常通过以下方式实现:

  1. The first argument is an integer which explicitly indicates the number of arguments to come.第一个参数是一个 integer ,它明确表示 arguments 的数量。
  2. The information is encoded inside the first argument such as the case for printf .该信息被编码在第一个参数中,例如printf的情况。

Often C macros are used to automate this and encapsulate some of these details.通常使用 C 宏来自动执行此操作并封装其中一些细节。 See: stdarg.h Macros请参阅: stdarg.h 宏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM