title: Custom C++ assert macro
body: <p>I stumbled upon an informative article: <a href="http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/">http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/</a>
  which pointed out a great number of problems that exist in my current suite of debugging macros. </p>
  
  <p>The full code for the final version of the macro is given near the end of the article if you follow the link.</p>
  
  <p>The general form as presented is like this (somebody please correct me if i am wrong in transposing it): </p>
  
  <pre><code>#ifdef DEBUG
  #define ASSERT(cond) \  
      do \  
      { \  
          if (!(cond)) \  
          { \  
              ReportFailure(#cond, __FILE__, __LINE__, 0); \
              HALT(); \
          } \  
      } while(0)  
  #else  
  #define ASSERT(cond) \  
      do { (void)sizeof(cond); } while(0) 
  </code></pre>
  
  <p>While thinking about modifying my code with what I have learned, I noticed a couple of interesting variations posted in the comments for that article: </p>
  
  <p>One was that you cannot use this macro with the ternary operator (i.e. <code>cond?ASSERT(x):func()</code>), and the suggestion was to replace the <code>if()</code> with the ternary operator and some parentheses as well as the comma operator. Later on another commenter provided this: </p>
  
  <pre><code>#ifdef DEBUG
  #define ASSERT(x) ((void)(!(x) &amp;&amp; assert_handler(#x, __FILE__, __LINE__) &amp;&amp; (HALT(), 1)))
  #else
  #define ASSERT(x) ((void)sizeof(x))
  #endif
  </code></pre>
  
  <p>I thought the use of logical and <code>&amp;&amp;</code> is particularly smart in this case and it seems to me that this version is more flexible than one using the <code>if</code> or even the ternary <code>?:</code>. Even nicer is that the return value of <code>assert_handler</code> can be used to determine if the program should halt. Although I am not sure why it is <code>(HALT(), 1)</code> instead of just <code>HALT()</code>. </p>
  
  <p>Are there any particular shortcomings with the second version here that I have overlooked? It does away with the <code>do{ } while(0)</code> wrapped around the macros but it seems to be unnecessary here because we don't need to deal with <code>if</code>s.</p>
  
  <p>What do you think?</p>