Variable Number of Arguments in C and C++

All this time I kept using printf and writing functions but never gave it much thought that printf accepts as many arguments as you want. How about we write a function that does the same?

The header file we’re going to use is cstdarg in C++ and stdarg.h in C. This header provides us one type and some macro functions to handle the argument list.

  • va_list : type to hold the argument list
  • va_start : macro to initialize the argument list
  • va_end : macro to end using the argument list
  • va_arg : macro to retrieve the next argument in ??? yep again..argument list.

Let’s use them in a function for a better understanding.

Still not clear how to use them? Here is how to start the function -

return_type name ( declaration_of_parameters, …)

Now we have some information about the arguments, we declare a variable, same as we declare ‘int a’

va_list list_name

va_start(list_name, type)

va_start initialise this list, same as we initialise some variable a=10

va_arg(list_name, type)

The va_arg macro works as a pointer which points to the next element in the list. One thing to notice here that it does not know when to end looking for the next element, so we have to take care of that in the function. For that, we have used the number of elements as the first argument.

va_arg() takes the “list” and “type” as parameters, it does not know the type of list itself, it returns whatever the “type” we pass.

va_end(list_name)

va_end() kind of wraps up the function so that it returns the result normally.

I have not gone much into details. This is just a simple illustration to get the idea. The same way we can find the maximum, minimum.

Keep coding, keep exploring!

Programmer, Loves to Code, Psychology Enthusiast, Believes in “Brevity is the soul of wit” !