Variadic arguments macro
suggest changeMacros with variadic args:
Let’s say you want to create some print-macro for debugging your code, let’s take this macro as an example:
#define debug_print(msg) printf("%s:%d %s", __FILE__, __LINE__, msg)
Some examples of usage:
The function somefunc() returns -1 if failed and 0 if succeeded, and it is called from plenty different places within the code:
int retVal = somefunc();
if(retVal == -1)
{
debug_print("somefunc() has failed");
}
/* some other code */
retVal = somefunc();
if(retVal == -1)
{
debug_print("somefunc() has failed");
}
What happens if the implementation of somefunc() changes, and it now returns different values matching different possible error types? You still want use the debug macro and print the error value.
debug_print(retVal); /* fails: the argument is not a string */
debug_print("%d",retVal); /* fails: this macro takes only one argument */
C99 added __VA_ARGS__ for macros that take a variable number of arguments:
Example:
#define debug_print(msg, ...) printf(msg, __VA_ARGS__); \
printf("\nError occurred in file:line (%s:%d)\n", __FILE__, __LINE__)
Usage:
int retVal = somefunc();
debug_print("retVal of somefunc() is-> %d", retVal);
This macro allows you to pass multiple parameters and print them, but now it forbids you from sending any parameters at all.
debug_print("Hey");
That is a syntax error. In C99 the invocation must supply at least one argument for the .... debug_print("Hey",) is also an error: an empty argument is not the same as an omitted one.
##__VA_ARGS__ is a GNU extension, not ISO C. It deletes the comma before __VA_ARGS__ when the variable arguments are omitted. C23 provides __VA_OPT__ for this in standard C.
Example:
#define debug_print(msg, ...) printf(msg, ##__VA_ARGS__); \
printf("\nError occurred at %s:%d\n", __FILE__, __LINE__)
Usage:
debug_print("Ret val of somefunc()?");
debug_print("%d",somefunc());