An example of use of varargs in C

Remember that arguments are passed on the stack. The va_start function contains the “magic” code to initialize the va_list with the correct stack pointer. It must be passed the last named argument in the function declaration or it will not work.

What va_arg does is use this saved stack pointer, and extract the correct amount of bytes for the type provided, and then modify ap so it points to the next argument on the stack.


In reality these functions (va_start, va_arg and va_end) are not actually functions, but implemented as preprocessor macros. The actual implementation also depends on the compiler, as different compilers can have different layout of the stack and how it pushes arguments on the stack.

Leave a Comment