Functions with variable number of arguments

In C/C++, functions can be written to take variable no. of arguments. Examples are printf, sprintf, snprintf etc. The prototype of printf functions looks like int printf(const char *format, …). These functions internally use macros such as va_start, va_arg, va_end etc to get the passed parameters. But, I have observed that for every function like printf, there is another similarly defined function which takes va_list instead of … . For example, vprintf is similar to printf and has int vprintf(const char *format, va_list ap) prototype. In the same way, vsprintf and vsnprintf are also defined. Till now, I did not know the reason and used to think of it as an unnecessary wrapper.

For example, if a wrapper called myprintf needs to be written over printf

int myprintf(const char* format, …){

va_list ap;

va_start(ap,format);

???????

va_end(ap);

}

In the above code, I can not put ‘printf’ in place of ??????. Because printf is expecting variable arguments (like i, j , l) and not va_list dataype. So, in place of ??????, I should call vprintf which takes va_list.

So, I observed that it is a good practice to write 2 functions in case of variable number of arguments. One which takes variable no. of arguments as … and the other one taking va_list. An example is given below.

void vfunction (char * format, va_list ap){

/*This function does the actual work*/

}

void function(char* format, …){

/*This function just redirects to vfunction which does the work */

va_list ap;

va_start(ap,format);

vfunction(format, ap);

va_end(ap);

}