Say I want to implement a function
void myprintf(const char* format, ...){
printf("Hello world!\n"),
printf(format, ...);
}
I.e. I want to pass along the varargs list to printf. Is there any convenient way to do this?
Say I want to implement a function
void myprintf(const char* format, ...){
printf("Hello world!\n"),
printf(format, ...);
}
I.e. I want to pass along the varargs list to printf. Is there any convenient way to do this?
No. However the library functions in the printf
family offer a vprintf
varaint that accepts a va_list
as an argument instead of ellipsis. And it is in fact a good practice to offer such a variant if you happen to be writing your own variable argument function.
Your wrapper would then be something like this:
void myprintf(const char* format, ...){
printf("Hello world!\n"),
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
}
With a little help of the preprocessor:
#include <stdio.h>
#define myprintf(...) \
do { \
printf("Hello world!\n"), \
printf(__VA_ARGS__); \
} while (0)
int main(void)
{
myprintf("%s %d\n", "Hello", 1);
return 0;
}