Programming with verbose option in C

Go To StackoverFlow.com

3

Does someone know how to write a program in C with the verbose option (the option to choose if messages are printed or not) in a nice way.

I mean, not writing an if(verbose) for each printf in the code.

Is there a more elegant solution?

2012-04-04 18:37
by synack
wrap it up in a macro - Collin 2012-04-04 18:38


9

Just use a (variadic) macro / vararg function that tests a flag before calling something like vfprintf.

/* Crude example. */
void my_log(char *format, ...)
{
    va_list args;
    if (!ok_to_log)
        return;

    va_start(args, format);
    vprintf(format, args);
    va_end(args);
}

EDIT As requested

How about a slightly modified gnu example:

#define eprintf(format, ...) do {                 \
    if (ok_to_print)                              \
        fprintf(stderr, format, ##__VA_ARGS__);   \
} while(0)
2012-04-04 18:38
by cnicutar
Nice, thank you - synack 2012-04-04 18:42
@Kits Don't forget about macros - cnicutar 2012-04-04 18:43
In fact you just have discovered them to me! thank - synack 2012-04-04 18:51
But then how should I #define the macro - synack 2012-04-04 18:59
@Kits I added a macro - cnicutar 2012-04-04 19:02
Cool, thanks!! - synack 2012-04-04 19:03


3

Make an array of function pointers

print_function_type fx[2] = {quietprint, verboseprint};

and instead of using an if when printing, use the correct element of the array

// if verbosemode is 0 call quietprint
// if verbosemode is 1 call verboseprint
fx[verbosemode]("%d", foo);
2012-04-04 18:41
by pmg
+1 Really elegant - cnicutar 2012-04-04 18:43
May be a mix of this and @cnicutar solution will do because I need the print instruction to be with a number of arguments variable and the arguments of different types - synack 2012-04-04 19:01


0

You can write your own printf-like function that checks for the verbose flag and then calls printf, if necessary.

2012-04-04 18:38
by ibid
Yes, but that is not easy - you would need your function to accept variable number of parameters for the internal printf.. - Marki555 2014-10-08 13:41
That's not difficult. Use vprintf internally - ibid 2014-10-23 07:30
Ads