Why is the Carry Flag set during a subtraction when zero is the minuend?

idlmn89 picture idlmn89 · Jul 3, 2016 · Viewed 18k times · Source

At the moment I write my own little library for arithmetic and logical operations for very big unsigned integers. To improve performance I decided to implement some functions in assembly. So here is my question. While subtracting two unsigned integers the Carry Flag is set when I subtract any number from 0.

But why is the Carry Flag set in this situation? The Carry Flag is only set when an overflow occurs, but if I subtract any number from zero I don't get an overflow. Or I am wrong?

Answer

Margaret Bloom picture Margaret Bloom · Jul 3, 2016

Carry flag is carry or borrow out of the Most Significant bit (MSb):

CF (bit 0) Carry flag — Set if an arithmetic operation generates a carry or a borrow out of the mostsignificant bit of the result; cleared otherwise. This flag indicates an overflow condition for unsigned-integer arithmetic. It is also used in multiple-precision arithmetic.

Don't associate the CF with the sign bit, in a subtraction CF is set whenever the minuend, treated as unsigned, is less than the subtrahend, treated as unsigned.
This is equivalent to an overflow condition, for signed numbers the equivalent flag is OF.

For an (unnecessary?) visual clue, in this 4-5 operation, it is the second borrow, the red one, that set the CF

Borrow and CF

Not if you subtract from zero, it comes naturally that for any number, but zero itself, you'll always have the CF set, as the subtrahend has at least one bit set.


Finally, some instructions let you change the sign bit without affecting the CF (see for example the logic operations or the behavior of neg).