Programming with detailed option in C

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

I mean by not writing if (verbose) for every printf in the code.

Is there a more elegant solution?

+3


source to share


3 answers


Just use the (varadic) macro / vararg function that checks the 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)

      

+9


source


Make an array of function pointers

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

      



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

// if verbosemode is 0 call quietprint
// if verbosemode is 1 call verboseprint
fx[verbosemode]("%d", foo);

      

+3


source


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

0


source







All Articles