BNE means branch on not equal. It jumps to a label when the zero flag, Z, is clear. In practice, that means a previous instruction produced a result that was not zero. If Z is set, execution continues with the next instruction instead of jumping. section 4.4.2 section 5.12
A common use is ending a loop with a register counter. Incrementing X with INX sets Z when X wraps from 255 back to 0. A following `bne clear_ram` returns to `clear_ram` while X is nonzero; when X becomes zero, the branch is not taken and the loop finishes. section 5.12
Listing 5.14 Clearing all RAM (example.s)
#1
lda #0
ldx #0
clear_ram:
sta $0000,x
sta $0100,x
sta $0200,x
sta $0300,x
sta $0400,x
sta $0500,x
sta $0600,x
sta $0700,x
inx
bne clear_ram
This loop clears all 2K of NES RAM. X can address only 256 values, so each pass stores zero into eight 256-byte memory blocks. BNE keeps repeating those eight stores until X wraps to zero. section 5.12
Use BNE carefully in branch code:
- Put a label at the loop start or branch destination, and let the assembler calculate the branch offset. section 4.4.2
- Keep the destination close enough: a branch can reach at most 129 bytes forward or 126 bytes backward from the branch instruction. section 4.4.2
- Check which instruction set Z immediately before BNE. In the RAM loop, INX supplies the test by making Z set only when X reaches zero. section 5.12
Skipping through sprite entries
Sprite data uses four bytes per sprite, with the Y position in the first byte. A loop can write 255 to that byte, increment X four times to reach the next sprite’s Y position, then use BNE to repeat until X wraps to zero. The result places every sprite below the visible screen during initialization. section 5.12
BNE is one member of the 6502 branch family. BEQ branches when Z is set, while other branch instructions test the negative, overflow, and carry flags. Choose BNE when the desired path is specifically the nonzero result. section 4.4.2
