title: How to write safe and user friendly c/c++ #define macros
body: <p>I have been thinking about how macros can be written to be safe, readable and intuitive. Proper use of them should be understood by the looks of them and when used incorrectly the compiler should tell you, and not let you introduce an obscure bug.</p>
  
  <p>When writing multiple line define macros I usually find myself constructing them like this to fullfill the desired criteria:</p>
  
  <pre><code>#define macro(x)    do{                      \
                          ... some code line ; \
                          ... some code line ; \
                      }while(0)
  </code></pre>
  
  <p>This way you can both...</p>
  
  <pre><code>if (a)
  {
      macro(a);
  }
  </code></pre>
  
  <p>and...</p>
  
  <pre><code>if (a)
      macro(a);
  else
  {
      ...
  }
  </code></pre>
  
  <p>A nice feature of this is that if you use them incorrectly you will get a compiler error. This will not compile for example:</p>
  
  <pre><code>if (a)
      macro(a)
  else
      b();
  </code></pre>
  
  <p>However, I have seen SW developers read this kind of macro construct and getting quite perplexed by it. Can you think of alternative ways to write macros that will not deceive the user in a way where they do something other than expected, and still are quite understandable when browsing a new piece of code? </p>
  
  <p>Also, can you find any problems with the do {} while(0) method? It could for example be a situation where you would expect the macro to behave a certain way and where this is not the case.</p>
  
  <p>The reason why i am not completely convinced the do {} while(0) method is good practice is that the macros themselves look a bit weird and take some explaining to anyone (some at least) who has not seen the construct before.</p>
  
  <p>Edit:</p>
  
  <p>Here is an example from one of the links in the comments (thanks!) that i like. It's quite readable I think:</p>
  
  <pre><code>#define MYMACRO(a,b)   \
      if (xyzzy) asdf(); \
      else (void)0
  </code></pre>
  
  <p>Is it possible to break it?</p>