Search code examples
cvariadic-functions

Go through all the arguments of a va_list without knowing in advance how many variable arguments it is composed of


My question is: Is there a way to go through all the arguments of a va_list without knowing a priori how many variable arguments it is composed of? On the web I found examples where the number of the ellipse's arguments was passed as the first argument and therefore, using a for loop, it was easy to navigate the elements. I wish my function was implicit.


Solution

  • Is there a way to go through all the arguments of a va_list without knowing a priori how many variable arguments it is composed of?

    No, there is not. The count (and type) of arguments has to be known, either use a sentinel value or pass a variable or have the count of arguments depend on other argument (I mean, like printf). The information about count of arguments is not stored anywhere - if that information is needed for your algorithm, you have to pass it yourself.

    You can write macros that will overload on number of arguments and pass the argument count as parameter. Or for a sentinel approach you can also write a macro that will pass NULL and if you are using gcc, there is a gcc attribute(sentinel) function attribute which will spawn warning is the sentinel NULL is missing.