title: How portable is casting -1 to an unsigned type?
body: <p>The other day, <a href="http://www.ddj.com/cpp/184403759" rel="noreferrer">I came across</a> this construct:</p>
  
  <pre><code>static_cast&lt;size_type&gt;(-1)
  </code></pre>
  
  <p>in some example C++ code, which is likely (depending on the details of where <code>size_type</code> is from) to be equivalent to the following C:</p>
  
  <pre><code>(size_t)(-1)
  </code></pre>
  
  <p>As I understand it, it works based on the fact that the representation of -1 in twos complement arithmetic is <code>11111...1</code>, for as many bits as you have, so this is a quick way of getting the maximum value that an unsigned type like <code>size_t</code> can hold. However, my understanding is also that C doesn't guarantee that twos complement will be used; if the C implementation uses one's complement, this will be 1 less than the the maximum value, and if it's using signed magnitude, it will be just over half the maximum value.</p>
  
  <p>Is there some wrinkle that I'm missing that insures that this works right regardless of the representation of signed integers being used? Does it differ between C and C++ (many surprising things do)?</p>