I have used variadic functions to wrap printf (or vprintf).
The following code works except for making mistake on the first variadic argument to warning_printf. Also, placing the string directly will change the ASCII character but it does not fix it as the message is still random.
What it prints is
[Warning]
®¯$ address: 0x87afae8a
Instead of
[Warning] Failed to initialize setting address: 0x87afae8a
Where the word Warning is colored properly (anyway it does not matter). But the msg_warn seems not being passed correctly. I tested adding more variables to this function. They all work fine except for only the first variadic argument msg_warn.
What is wrong with my code?
void colorful_printf( const char* header, const char* color, const char* fmt, ... )
{
printf("[%s%s%s] ", color, header, RESET_ANSI_COLOR);
va_list args;
va_start( args, fmt );
vprintf(fmt, args);
va_end( args );
}
void warning_printf( const char* fmt, ... )
{
va_list args;
va_start( args, fmt );
colorful_printf("Warning", WARNING_COLOR, fmt, args);
va_end( args );
}
char msg_warn[] = "Failed to initialize setting";
warning_printf( "%s address: 0x%2x", msg_warn, address );
Online compiler: link
va_listinstead of....va_listinstead of...and the...functions create ava_listand then call the function that takes theva_listto do the real work. We will need to come to a consensus on whether it is OK as a duplicate despite the mismatch between C++ and C, or contemplate retagging it as C++ and C (ouch!).