title: Revising the syntax of Duff's device - Is this legal C/C++?
body: <p>Only last night I encountered the curious <a href="http://en.wikipedia.org/wiki/Duff%27s_device" rel="nofollow">Duff's device</a> for the first time. I've been doing some reading on it, and I don't think it's that daunting to understand. What I am curious about is the strange syntax (from Wikipedia):</p>
  
  <pre><code>register short *to, *from;
  register int count;
  {
    register int n = (count + 7) / 8;
    switch(count % 8) {
    case 0: do {    *to = *from++;
    case 7:         *to = *from++;
    case 6:         *to = *from++;
    case 5:         *to = *from++;
    case 4:         *to = *from++;
    case 3:         *to = *from++;
    case 2:         *to = *from++;
    case 1:         *to = *from++;
      } while(--n &gt; 0);
    }
  }
  </code></pre>
  
  <p>I was reading the C++ standard definition of a <a href="http://www.open-std.org/jtc1/sc22/open/n2356/stmt.html#stmt.switch" rel="nofollow">switch statement</a> (please let me know if that's outdated, I'm not familiar with Open-Std.org). So far as I can understand case statements are just simplified jump statements for use by the switch statement.</p>
  
  <p>The switch itself completely ignores the nested do-while, and the loop ignores the case statements. Since the switch jumps inside of the loop, the loop is executed. The switch is there to cover the remainder (from the division by 8), and the loop handles the portion that is evenly divisible. This all makes sense.</p>
  
  <p>My question then is why the awkward syntax? It occurs to me that the loop could be written such that all of the case statements are contained within, yes? I see nothing in the standard that prohibits this behavior, and it compiles correctly under GCC 4.7, so is the following considered legal?</p>
  
  <pre><code>register short *to, *from;
  register int count;
  {
    register int n = (count + 7) / 8;
    switch (count &lt;= 0 ? 8 : count % 8)
    {
      do
      {
        case 0:         *to = *from++;
        case 7:         *to = *from++;
        case 6:         *to = *from++;
        case 5:         *to = *from++;
        case 4:         *to = *from++;
        case 3:         *to = *from++;
        case 2:         *to = *from++;
        case 1:         *to = *from++;
        default:        ; // invalid count, suppress warning, etc.
      } while(--n &gt; 0);
    }
  }
  </code></pre>
  
  <p>To me this makes the intent of the code much clearer. Thanks for any feedback. ;)</p>
  
  <p><strong>Edit:</strong> As noted below, the original code was written for C and had implicit int for the <em>count</em> and <em>n</em> variables. Since I tagged it C++ I've modified that.</p>
  
  <p><strong>Edit 2:</strong> Modified the revised example code to account for invalid count values.</p>