1

I want to write an conditional printf, something like this

class ConditionalPrintf
{
public:
    ConditionalPrintf(bool print)
        : print_(print)
    {}

   void printf(int x, double y, char b, const char* format, ...) const
   {
        // use x, y and b

        va_list argptr;
        va_start(argptr, format);

        if (print_)
            printf(format, argptr);

        va_end(argptr);
   }

private:
   bool print_;
};

But it prints garbage. Is there anything wrong? May implicit this parameter change things?

Also, if this isn't good idea whatsoever, what other solutions are there? I just don't want to write if (print) printf(...) billion times.

Mister Nobody
  • 113
  • 1
  • 6
  • have a look at vprintf: http://en.cppreference.com/w/cpp/io/c/vfprintf – Richard Hodges Jul 06 '16 at 12:32
  • No I don't want to use it, I need to understand what's wrong with my program. – Mister Nobody Jul 06 '16 at 12:35
  • 2
    what's wrong with your program is that you're not using it. It's designed for forwarding a va_list into printf! – Richard Hodges Jul 06 '16 at 12:37
  • 2
    val_list is an argument for vprintf, notfor printf. Thus you see garbage. Use vprintf – dimba Jul 06 '16 at 12:37
  • I feel sort of bad marking this C++ question a duplicate of a C question, but since you are using C functions and the answer is exactly the same... – Cody Gray - on strike Jul 06 '16 at 12:38
  • 2
    You **cannot** wrap `printf`. You **must** wrap `vprintf` instead. There is a reason why every standard varargs function has a "v" counterpart. That's the way varargs work. (Now that we have C++11 you may be able to wrap printf with a C++11 variadic template, but there's no reason to). – n. m. could be an AI Jul 06 '16 at 12:41
  • Well, and can I just call `printf_another(format, argptr)` from that code? (printf_another is another member function) – Mister Nobody Jul 06 '16 at 12:46

1 Answers1

3

vprintf forwards the arg list to printf

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

class ConditionalPrintf
{
public:
    ConditionalPrintf(bool print)
        : print_(print)
    {}

   void printf(int x, double y, char b, const char* format, ...) const
   {
        // use x, y and b

        va_list argptr;
        va_start(argptr, format);

        if (print_)
            vprintf(format, argptr);

        va_end(argptr);
   }

private:
   bool print_;
};
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142