title: distance between two signed numbers
body: <p>The distance between two numbers is often calculated like that:</p>
  
  <pre><code>long distance(long x, long y)
  {
       return x &gt; y ? x - y : y - x;
  }
  </code></pre>
  
  <p>However with signed <code>x</code> and <code>y</code> these subtractions there may overflow and so that function can invoke undefined behavior both in C and C++.</p>
  
  <p>One way out of that issue is to use unsigned type to represent resulting distance. Distance can not be negative so signed type is not needed. Distance between minimum and maximum of signed type should fit into unsigned type of same size. (<strong>Edit:</strong> As chux answered it was not entirely correct assumption.) So I did modify the first function like that:</p>
  
  <pre><code>unsigned long distance(long x, long y)
  {
      return (x &gt; y) ? (unsigned long)x - (unsigned long)y
                     : (unsigned long)y - (unsigned long)x;
  }
  </code></pre>
  
  <p>Does it now correctly calculate the distance between two signed longs in standard conforming and portable manner? If it does not, what would be the fix?</p>