How does the following code work?
#define ENABLE_DEBUG 1
#if ENABLE_DEBUG
#define LOG_MSG printf
#else
#define LOG_MSG(...)
#endif
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Depending on the value of
ENABLE_DEBUG,LOG_MSGis either defined to be an alias forprintf()or it is defined as a no-op macro. It is implied that you can change the value to0to disable debugging. This is a common technique for making it easy to switch between debugging builds which display lots of output and release builds which are quiet.This makes it an alias for
printf().And this defines it as an empty macro. Notice that here it has a set of parentheses, which means the macro takes parameters. It has nothing afterwards which means it expands to absolutely nothing. And the
...indicates that this macro can take a varying number of arguments. This syntax is a C99 extension so it may not be available on older C compilers.The result is that a
LOG_MSG()call will either print a message or do nothing depending on whether logging is enabled.For what it’s worth, whoever authored this macro could’ve done a better job by replacing the first definition with one using the
...syntax (which he/she is clearly familiar with), printing to stderr instead of stdout: