Search code examples
cmacrosvariadic-functions

Variadic Functions in C Concept


I'm not very clear on the concept of variadic functions in C. In practice, what do macros like va_list, va_start, va_end represent?

From what I understand va_start declares a list, va_start inizialize it and va_end it's a cleanup. But I don't understand how to use them in practice and it's not clear to me what the macros represent when I look at them at a lower level of abstraction.

A more practical explanation of this concept with some examples if possible would be very useful to me, thanks.


Solution

  • In the early days of C language, the passing parameters contract was that parameters were put into the stack in reverse order. And neither the type nor the number of parameters were part of the function declaration, only its return value type. It was then easy to handle a variable number of parameters (at least in assembly code) provided that number could be deduced from the fix part. As already said in comments, it is exactly the way the printf and scanf functions from the standard library work.

    The va_* things from stdarg.h were later added as a portable way to handle those variadic functions directly in C language, and they were designated as opaque macros. The rationale was that the the gory details of passing parameters were details for the language implementations, and the implementation only had to provide a way for the C programmer to be able to access the parameters the hard way meaning here knowing their order and type at run time instead of at compile time.

    In common implementations, they are just a way to extract a pointer in the program stack to the frame containing the parameters and to iterate that frame.

    For an example of usage, you could have a look the the excellent cppreference site