Reputation: 8933
Take a function like printf that accepts a variable number of arguments what I would like to do is pass these variable number of functions to a sub function without changing their order. An example of this would be aliasing the printf function to a function called console ...
#include <stdio.h>
void console(const char *_sFormat, ...);
int main () {
console("Hello World!");
return 0;
}
void console(const char *_sFormat, ...) {
printf("[APP] %s\n", _sFormat);
}
If I did for example console("Hello %s", sName)
, I would want the name to be passed to the printf function also, but it has to be able to continue to accept a varable number of arguments like the printf already does.
Upvotes: 1
Views: 301
Reputation: 19965
Here's what you want:
#include <stdio.h>
#include <stdarg.h>
void console(const char *_sFormat, ...);
int main () {
console("Hello World!");
return 0;
}
void console(const char *_sFormat, ...) {
va_list ap;
va_start(ap, _sFormat);
printf("[APP] ");
vprintf(_sFormat, ap);
printf("\n");
va_end(ap);
}
Upvotes: 4
Reputation: 57555
There'll be another problem (noted by gf) -- you should probably concatenate the string in printf
and the _sFormat
parameter -- I doubt that printf
is recursive -- hence the format statements in the first parameter wont be read!
Hence maybe such a solution would be nicer:
#include <stdarg.h>
void console(const char *_sFormat, ...)
{
char buffer[256];
va_list args;
va_start (args, _sFormat);
vsprintf (buffer,_sFormat, args);
va_end (args);
printf("[APP] %s\n", buffer);
}
Types/functions used:
Upvotes: 2