How do I use a macro with variable arguments?

272 views Asked by At

see my code

#include<stdarg.h>

#define DPRINTF(_fmt, ...) debugPrintf(_fmt,__VA_ARGS__)

void debugPrintf(const char *fmt, ...)
{
char buf[128];  
va_list ap;  

va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
fprintf(stderr,"%s",buf);        
return;
}

main()
{
int a=10;  
DPRINTF("a is %d",a);
DPRINTF("WHY THIS STATEMENT GETS ERROR");

}

why this code can not be compile.?? when i m commenting

 //DPRINTF("WHY THIS STATEMENT GETS ERROR");

it work correct..

Is there any way to write debug with ... (variable argument) to also handle such condition where i do not want to pass any variable

2

There are 2 answers

0
Jens Gustedt On BEST ANSWER

Just use

#define DPRINTF(...) debugPrintf(__VA_ARGS__)

variadic macros, other than variadic functions, don't need a fixed argument.

1
Luchian Grigore On

Try

#define FOO(fmt, ...) printf(fmt, ##__VA_ARGS__)

The double hash is there in case of no arguments after the first one.