Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your method does not work for several reasons:</p> <ul> <li><p>Assuming <code>x</code> and <code>y</code> are signed values, the subtraction could overflow. Not only does this result in <em>undefined behavior</em> according to the C standard, but on typical implementations where overflow wraps, it will give the wrong results. For instance, if <code>x</code> is <code>INT_MIN</code> and <code>y</code> is <code>1</code>, <code>x-y</code> will yield <code>INT_MAX</code>, which does not have its high bit set.</p></li> <li><p>If <code>x</code> and <code>y</code> are unsigned values, then <code>x=UINT_MAX</code> and <code>y=0</code> is an example where you get the wrong answer. You'd have to impose a condition on the values of <code>x</code> and <code>y</code> (for instance, that neither has its high bit set) in order for this test to work.</p></li> </ul> <p>What it comes down to is that in order to perform comparisons by testing the "high bit", you need one more bit than the number of bits in the values being compared. In assembly language on reasonably-CISC-ish architectures, the carry flag provides this extra bit, and special conditional jump instructions (as well as carry/borrow instructions) are able to read the value of the carry flag. C provides no way to access such a carry flag, however. One alternate approach might be to use a larger integer type (like <code>long long</code>) so that you can get an extra bit in your result. Good compilers will translate this to a read of the carry flag, rather than actually performing larger arithmetic operations.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload