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 a va_start
macro that needs to know how many arguments there, but the printf
& ... that are using va_list
don't need the argument count. How can I create a function that doesn't need the argument count like printf
?
Let's say I want to create a function that takes a va_list
and instead of using it, passes it to another function that requires a va_list
? (so in pseudocode, it would be like void printfRipOff(const char* format, ...) {printf(format, ...);}
)
Let's say I want to create a function that takes a va_list
and instead of using it, passes it to another function that requires a va_list
?
Look at function vprintf( const char * format, va_list arg );
for one example of a function that takes a va_list
as an input parameter.
It is basically used this way:
#include <stdio.h>
#include <stdarg.h>
void CountingPrintf(const char* format, ...)
{
static int counter = 1;
printf("Line # %d: ", counter++); // Print a Counter up front
va_list args;
va_start(args, format); // Get the args
vprintf(format, args); // Pass the "args" through to another printf function.
va_end(args);
}
int main(void) {
CountingPrintf("%s %s\n", "Hello", "World");
CountingPrintf("%d + %d == %d\n", 2, 3, 2+3);
return 0;
}
Line # 1: Hello World
Line # 2: 2 + 3 == 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With