Demonstrates the use of the do{ ... }while(0) hack to secure the use of multi-line macros in conditionals. Note: this code does not compile.
#include <iostream>
#define SAFE_LOG_FIRST_N(arg,n) \
do{ \
static int LOG_OCCURRENCES = 0; \
if (LOG_OCCURRENCES <= n) ++LOG_OCCURRENCES; \
if (LOG_OCCURRENCES <= n) std::cout<<arg; \
} while(0)
#define LOG_FIRST_N(arg,n) \
{ \
static int LOG_OCCURRENCES = 0; \
if (LOG_OCCURRENCES <= n) ++LOG_OCCURRENCES; \
if (LOG_OCCURRENCES <= n) std::cout<<arg; \
}
int main(int argc, const char * argv[]) {
if(true)
SAFE_LOG_FIRST_N("Om mane padme om", 1);
else
exit(5);
if(true)
LOG_FIRST_N("Om mane padme om", 1);
else // fails here with "expected expression"
exit(5);
return 0;
}