Last active
November 23, 2015 07:32
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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