Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming with verbose option in C

Tags:

c

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?

like image 798
synack Avatar asked Oct 21 '25 04:10

synack


2 Answers

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)
like image 81
cnicutar Avatar answered Oct 23 '25 21:10

cnicutar


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);
like image 29
pmg Avatar answered Oct 23 '25 22:10

pmg