title: Is detecting unsigned wraparound via cast to signed undefined behavior?
body: <p>I'm using a <code>uint16_t</code> as a sequence counter in a network protocol.  This counter commonly wraps around as expected.  When a receiver gets a packet it checks this counter against the most recently received to see whether it's a new packet or an out of order packet.</p>
  
  <p>Wraparound needs to be taken into account when comparing sequence numbers.  So if for example the last sequence number was <code>0x4000</code>, then a sequence number from <code>0x4001</code> to <code>0xBFFF</code> is newer, and a sequence number from <code>0xC000</code> to <code>0xFFFF</code> and from <code>0x0000</code> to <code>0x3FFF</code> is smaller.</p>
  
  <p>The way I'm currently doing this is as follows:</p>
  
  <pre><code>uint16_t last;
  uint16_t current;
  ...
  // read in values for last and current
  ...
  if ((int16_t)(current - last) &gt; 0) {
      printf("current is newer\n");
  } else {
      printf("current is older (or same)\n");
  }
  </code></pre>
  
  <p>By subtracting the two and treating the result as a <code>int16_t</code>, I can easily see which is greater and by how much.  So for example if the current sequence number is at least 5 less that the last, i.e <code>((int16_t)(current - last) &lt; -5)</code>, I can assume this is not due to normal packet reordering and drop the packet.</p>
  
  <p>I realize that signed wraparound is undefined, however in this case I'm treating an unsigned value as signed for the sake of doing comparisons.  Does this invoke undefined behavior, and if so what would be a better way to do this type of comparison?</p>