Why does CMP (compare) sometimes sets a Carry Flag in 8086 assembly?

faul picture faul · Nov 7, 2011 · Viewed 24.3k times · Source

I've been reading around and with the 8086 Instruction Set, it says that a CMP (compare) can set the Carry Flag. I understand that a compare subtracts two operands but I was wondering if anyone can provide an example when that is the case.

I just can't grasp the idea of adding a number and a negative number will set the carry flag. I've read into the borrow flag but I just needed an example to clarify my understanding of a compare instruction.

Also, I understand that if 3 - 5 = -2 would set the negative flag... when is carry set?

Answer

Sparafusile picture Sparafusile · Nov 7, 2011
  • The carry flag is set after an operation that resulted in an underflow or overflow. For example, subtracting 10 from 6 will result in an underflow and set the carry flag. Similarly, adding 1 to the maximum value of the register will result in an overflow and set the carry flag.
  • The carry flag is also modified during a shift operation, it is set to the value of the last bit shifted out of the destination register.
  • Bit testing will place the value of the tested bit into the carry flag. Opcodes that do this: BT, BTC, BTR, and BTS.
  • Instructions that affect the Carry Flag directly: CLC, CMC, and STC.
  • During a comparison, the carry flag is set just as if the two operands had been subtracted.
  • During a negation (NEG), the carry flag is set unless the operand is zero, in which case it is cleared.