title: Bitmask switch statement
body: <p>I have this code in a section of my project:</p>
  
  <pre><code>enum myEnum
  {
      invalid = -1,
      val1 = 1,
      val2 = 2,
      val3 = 4
  };
  
  int bitmask = val1 | val3;
  
  if(bitmask &amp; val1)
      ...
  if(bitmask &amp; val2)
      ...
  if(bitmask &amp; val3)
      ...
  </code></pre>
  
  <p>This is fine, and it works perfectly, but i've always wondered if it could be done with a switch. I was thinking something along the lines this:</p>
  
  <pre><code>int checkMask(int&amp; mask)
  {
      for(int i = 0; mask; mask &amp;= ~(1 &lt;&lt; i++))
      {
          if(mask &amp; (1 &lt;&lt; i))
          {
              int ret = mask &amp; (1 &lt;&lt; i);
              mask &amp;= ~ret;
              return ret;
          }
      }
  
      return invalid;
  }
  
  #define START_BITMASK_SWITCH(x) int xcopy = x; while(xcopy) { switch(checkMask(xcopy))
  #define END_BITMASK_SWITCH };
  
  int bitmask = val1 | val3;
  
  START_BITMASK_SWITCH(bitmask)
  {
      case val1:
          ...
          break;
      case val2:
          ...
          break;
      case val3:
          ...
          break;
  }
  END_BITMASK_SWITCH
  </code></pre>
  
  <p>so my questions are:
  <li>have i just solved my problem? i suppose i have, but is it a clean solution?
  <li>is there a simpler way of accomplishing this?
  <li>is it a bad idea to mix #defines and functions?</p>