This page is a mirror of Tepples' nesdev forum mirror (URL TBD).
Last updated on Oct-18-2019 Download

N flag after CMP/CPX/CPY instruction

N flag after CMP/CPX/CPY instruction
by on (#93948)
Has anyone any clue how it is used ?

Honnestly I always use CMP/CPX/CPY instruction in pairs with the Z flags (to test equality) or with the C flag, to test >= or <

Also V is affected and I'm pretty sure it's purpose is to compare signed numbers, although I don't remember ever using it.

However, what about the N flag ? Supposedly it would be set as if a SBC instruction was used, exept the registers aren't affected.

by on (#93951)
http://www.obelisk.demon.co.uk/6502/reference.html#CMP

Not exactly like if SBC was used, just a straight subtraction (carry is not involved), and then N is bit 7 of the result.

I suppose it could be useful to know if a subtraction would result in bit 7 being set without having to clobber A to do it. It's not one of your normal comparison operations, but it might have some use. It's not appropriate for > or <, but if you ever want to know this:

if (A-B modulo 256) > 127

I guess that's what it is.

by on (#93952)
I think the point is to check for >= and < on signed numbers, similar to how you would use the carry flag to check for >= and < on unsigned numbers. The problem is that overflow will give an incorrect result.

Code:
lda #$10            ; 16
cmp #$F0            ; -16
bpl IsGreaterThan   ; will branch, 16 > -16

lda #$10            ; 16
cmp #$00            ; 0
bpl IsGreaterThan   ; will branch, 16 > 0

lda #$10            ; 16
cmp #$20            ; 32
bpl IsGreaterThan   ; will NOT branch, 16 < 32

; Overflow: 122 - (-32) = 154
lda #$70            ; 122
cmp #$E0            ; -32
bpl IsGreaterThan   ; will NOT branch, even though 122 > -32

by on (#93955)
OK so the N flag can be used for signed comparaison only if there is no overflow, and there is no way to detect overflow other than using SBC.
How unintuitive.