This is what was said about va_arg in the famous link below:
http://www.cplusplus.com/reference/cstdarg/va_arg/
Notice also that va_arg does not determine either whether the retrieved argument is the last argument passed to the function (or even if it is an element past the end of that list). The function should be designed in such a way that the number of parameters can be inferred in some way by the values of either the named parameters or the additional arguments already read.
In addition, in the so-called book from which I read about va_arg , all examples made sure that one of the arguments fixed always the number / number of variables that we will pass. And this count is used in the loop, which advances va_arg to the next element, and the loop condition (using the counter) ensures that it exits when va_arg receives the last argument in the variable list. This seems to confirm over the paragraph from the site, which states that "the function should be designed in such a way........" (above) .
So, in stupid words, va_arg is kind of stupid. But in the following example, taken from this site for va_end , va_arg suddenly seems smart. When the end of the argument list is a variable of type char* , it returns a NULL pointer. How it is? The very top paragraph that I outlined says:
"va_arg does not determine either whether the retrieved argument is the last argument passed to the function (or even if it is an element past the end of that list"
and, in addition, there is nothing in the next program that would guarantee that the NULL pointer should be returned at the end of the variable argument list. So how va_arg return a NULL pointer here at the end of the list
#include <stdio.h> /* puts */ #include <stdarg.h> /* va_list, va_start, va_arg, va_end */ void PrintLines (char* first, ...) { char* str; va_list vl; str=first; va_start(vl,first); do { puts(str); str=va_arg(vl,char*); } while (str!=NULL); va_end(vl); } int main () { PrintLines ("First","Second","Third","Fourth",NULL); return 0; }
Output
First Second Third Fourth
Link to the source code of the program