0

When looking for how to wrap a function with variadic length argument, what I often see as an answer is not a solution but a workaround. Let's change the example from printf to a function printfln written in a library and I have no control over the library and I cannot add anything there. Now, I have another function double_printfln that should call printfln two times. This time we cannot use vprintf workaround.

How to do this?

https://wandbox.org/permlink/q8wF51qLu8JdYv0o

#include <stdio.h>
#include <stdarg.h>

int printfln(const char *format, ...)
{
    int result;
    va_list args;
    va_start(args, format);
    result = vprintf(format, args);
    printf("\n");
    va_end(args);

    return result;
}

int double_printfln(const char *format, ...)
{
    int result;
    va_list args;
    va_start(args, format);
    result = printfln(format, args);
    result += printfln(format, args);
    va_end(args);
    return result;
}

int main()
{
    int x=7;
    char text[20] = "Hello";
    double_printfln("%s, %d", text, x);
    return 0;
}


Solution

For those who face with a similar problem, this is how I fixed it. This is actually another workaround but in a better way:

int double_printfln(const char *format, ...)
{
    char line[512];
    int result;
    va_list args;
    va_start(args, format);
    memset(line, 0x00, sizeof line);
    vsprintf(line, format, args);
    va_end(args);

    result = printfln(line);
    result += printfln(line);

    return result;
}
mercury
  • 189
  • 1
  • 15
  • 2
    You can't. See: [Forward an invocation of a variadic function in C](https://stackoverflow.com/questions/150543/forward-an-invocation-of-a-variadic-function-in-c) – Marco Bonelli Oct 15 '20 at 23:41
  • I did. You want to call `printfln` from another variadic function passing the same arguments two times. The answer is that you cannot do this. If you mean something else, then you'll need to edit your question to make it clear. – Marco Bonelli Oct 15 '20 at 23:44
  • @MarcoBonelli, Sorry for the typo. I need to call `printfln` two times. – mercury Oct 15 '20 at 23:45
  • Yeah, `printfln`, I meant that. It's not possible as I said. The post I linked in my first comment explains it. – Marco Bonelli Oct 15 '20 at 23:46

0 Answers0