简体   繁体   中英

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.

  1. Is it an array of void pointers?
  2. Is it a linked list of void pointers?
  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.

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. 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..)

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).

It is then the responsibility of the callee to detect and reference these arguments from the stack. 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). To determine the number of arguments, this information must be communicated. This is often achieved in the following ways:

  1. The first argument is an integer which explicitly indicates the number of arguments to come.
  2. The information is encoded inside the first argument such as the case for printf .

Often C macros are used to automate this and encapsulate some of these details. See: stdarg.h Macros

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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