title: Is there a safe way to get the unsigned absolute value of a signed integer, without triggering overflow?
body: <p>Consider a typical absolute value function (where for the sake of argument the integral type of maximum size is long):</p>
  
  <pre><code>unsigned long abs(long input);
  </code></pre>
  
  <p>A naive implementation of this might look something like:</p>
  
  <pre><code>unsigned long abs(long input)
  {
      if (input &gt;= 0)
      {
          // input is positive
          // We know this is safe, because the maximum positive signed
          // integer is always less than the maximum positive unsigned one
          return static_cast&lt;unsigned long&gt;(input);
      }
      else
      {
          return static_cast&lt;unsigned long&gt;(-input); // ut oh...
      }
  }
  </code></pre>
  
  <p>This code triggers undefined behavior, because the negation of <code>input</code> may overflow, and triggering signed integer overflow is undefined behavior. For instance, on 2s complement machines, the absolute value of <code>std::numeric_limits&lt;long&gt;::min()</code> will be 1 greater than <code>std::numeric_limits&lt;long&gt;::max()</code>.</p>
  
  <p>What can a library author do to work around this problem?</p>