开发者

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 varia开发者_运维百科ble 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜