Using the <stdarg.h> header, one can make a function that has a variable number of arguments, but:
To start using a
va_list, you need to use ava_startmacro that needs to know how many arguments there, but theprintf& ... that are usingva_listdon't need the argument count. How can I create a function that doesn't need the argument count likeprintf?Let's say I want to create a function that takes a
va_listand instead of using it, passes it to another function that requires ava_list? (so in pseudocode, it would be likevoid printfRipOff(const char* format, ...) {printf(format, ...);})
Functions like
printf()andscanf()have the format string argument that tells them the number and types of the arguments that must have been provided by the function call.If you're writing your own function, you must have some way of knowing how many arguments were provided and their types. It may be that they are all the same type. It may be that they're all pointers and you can use a null pointer to indicate the end of the arguments. Otherwise, you probably have to include a count.
You can do that as long as provided the called function expects a
va_list. There are caveats (see C11 §7.16 Variable arguments) but they're manageable with a little effort.A very common idiom is that you have a function
int sometask(const char *fmt, ...)and a second functionint vsometask(const char *fmt, va_list args), and you implement the first as a simple call to the second:The second function does the real work, of course, or calls on other functions to do the real work.
In the question, you say:
No; the
va_startmacro only needs to know which argument is the one before the ellipsis — the argument name before the, ...in the function definition.In a comment, you say:
As noted by abelenky in a comment, you need to use
vsprintf():That assumes that the
formattedStringhas enough space in the array for the formatted result. It isn't immediately obvious how that's organized, but presumably you know how it works and it works safely. Consider usingvsnprintf()if you can determine the space available in theformattedString.