Sajib
Sajib

Reputation: 414

Calling a printf with __VA_ARGS__ not working in a function but works in a macro

The following macro works:

#define DEBUG(msg, ...) printf(msg, __VA_ARGS__)

But when I add my own function, it says error: '__VA_ARGS__' was not declared in this scope. My code:

void Debug(const char* msg, ...) {
    printf(msg, __VA_ARGS__);
}

#define DEBUG(msg, ...) Debug(msg, __VA_ARGS__)

Is there any way to do so?

Upvotes: 2

Views: 2699

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596352

__VA_ARGS__ simply does not exist outside of a variadic macro. For what you are attempting, use vprintf() instead of printf(), eg:

void Debug(const char* msg, ...) {
    va_list args;
    va_start(args, msg);
    vprintf(msg, args);
    va_end(args);
}

#define DEBUG(msg, ...) Debug(msg, __VA_ARGS__)

Upvotes: 4

NutCracker
NutCracker

Reputation: 12263

Variadic parameter pack is your friend in this case:

template< typename ... Args >
void Debug( const char * msg, Args ... args ) {
    printf( msg, args ... );
}

Upvotes: 3

Related Questions