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?
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);
}
How about a slightly modified gnu example:
#define eprintf(format, ...) do { \
if (ok_to_print) \
fprintf(stderr, format, ##__VA_ARGS__); \
} while(0)
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);
You can write your own printf-like function that checks for the verbose flag and then calls printf, if necessary.