title: Why does stdlib.h's abs() family of functions return a signed value?
body: <p>The negative implication of this is noted in the man page:</p>
  
  <blockquote>
    <p>NOTES
           Trying  to  take the absolute value of the most negative integer is
    not
           defined.</p>
  </blockquote>
  
  <p>What's the reasoning behind this and what's the best recourse for a person who would like to avoid undefined behavior? Do I have to resort to something like:</p>
  
  <pre><code>unsigned uabs(signed val) {
      return val &gt; 0
          ? val
          : (val == 1U &lt;&lt; ((sizeof(val) * 8) - 1))
              ? -1U
              : -val;
  }
  </code></pre>
  
  <p>(Intentionally hacky to emphasize displeasure with stdlib ;-)</p>
  
  <h2>Example</h2>
  
  <p>Say you had a 4-bit signed value (for ease of understanding). unsigned max is 15, signed (positive) max is 7, signed (negative) min is -8, so abs(-8) won't fit into a signed value. Sure, you can represent it as -8, but then division and multiplication with the result don't work as expected.</p>