Skip to content

Instantly share code, notes, and snippets.

@eelstork
Last active November 23, 2015 07:32
Show Gist options
  • Save eelstork/bf3107a8ba59fb5bd4ae to your computer and use it in GitHub Desktop.
Save eelstork/bf3107a8ba59fb5bd4ae to your computer and use it in GitHub Desktop.
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment