Search code examples
cprintfcustomizationvariadic-functions

Wrap printf with custom condition


I want to only printf if some condition is true. I know printf is a variadic function but sadly I can't seem to find any thread here explaining I can wrap it.

Basically every in the code where I'd write :

printf(" [text and format] ", ... args ...);

I want to write something like

my_custom_printf(" [text and format] ", ... args ...);

Which then is implemented like this :

int my_custom_printf(const char* text_and_format, ... args ...)
{
    if(some_condition)
    {
        printf(text_and_format, ... args...);
    }
}

A first version of the condition would be independent of the args (it would be on some global variable), but it might be in the future that it's a condition on argument that's wanted.

Anyway, right now I just need the syntax for ... args ... in the prototype and the body of my_custom_printf.

I'm using GCC but I don't know which C standard - but we can just try stuff out.


Solution

  • You can use vprintf:

    #include <stdio.h>
    #include <stdarg.h>
    #include <stdbool.h>
    
    static bool canPrint = true;
    
    int myprintf(const char *fmt, ...)
    {
        va_list ap;
        int res = 0;
    
        if (canPrint) {
            va_start(ap, fmt);
            res = vprintf(fmt, ap);
            va_end(ap);
        }
        return res;
    }
    
    int main(void)
    {
        myprintf("%d %s\n", 1, "Hello");
        return 0;
    }