Skip to content
systemcoding.dev
Assembly

Write Counted Loops on the 6502 With DEX and BNE

Write counted loops on the 6502 with DEX and BNE: count down to zero, avoid the 256-iteration trap, nest loops for counts above 255 and work out the cycle cost.

6 min read
Summarize in AI
Flat illustration of an assembly listing with addresses and mnemonics, with the Arm, RISC-V and Intel logos.

The 6502 has no for statement and no loop instruction. A loop is a label, a body, a change to a counter and a conditional branch back to the label. The idiom every 6502 programmer reaches for first is a countdown: load a register with the number of repetitions, run the body, DEX, and BNE back. It is two instructions of overhead, it needs no compare, and it ends on the flag that the decrement already set. This post builds that loop, shows the three mistakes that break it, extends it to counts above 255, and works out how many cycles it takes using the figures from the MOS Technology programming manual.

The basic countdown

A counted loop that clears 16 bytes of memory starting at $0300:

clear16.sasm
        .org $0200
start:  LDA #$00            ; the value to store
        LDX #$10            ; X = 16, the number of iterations
loop:   STA $02FF,X         ; store at $02FF + X
        DEX                 ; X = X - 1, sets Z when X reaches zero
        BNE loop            ; branch back while X is not zero
        BRK

Follow the registers. X begins at 16. The first store goes to $02FF + 16 = $030F, then X becomes 15. The last pass has X = 1 and stores to $0300, after which DEX makes X zero, Z is set and BNE falls through. Sixteen iterations ran, and they cleared $0300 through $030F in reverse order:

Text
[$0300..$030F] = 00 (16 bytes)   A = $00   X = $00   Z = 1

The store address $02FF,X looks odd, because it is one below the target. The reason is the loop's value range: X takes the values 16 down to 1 and never 0, so to hit $0300 on the last pass the base must sit one byte lower. If you want X to run from 15 down to 0 and address $0300,X naturally, you need a different loop end, covered below.

What DEX and BNE do together

DEX subtracts one from X and sets N and Z from the result. It does not touch the carry. BNE branches when Z is clear, which means the last result was nonzero. No CPX #$00 is needed because the decrement did the compare for free. This is the pattern behind most 6502 loops, and it is why X is called the counter.

The same structure works with Y (DEY, BNE), and with memory counters through DEC:

memloop.sasm
count   = $10

        LDA #$05
        STA count
loop:   ; body goes here
        DEC count           ; memory decrement sets N and Z
        BNE loop

DEC count takes 5 cycles in zero page, against 2 for DEX, so memory counters are for loops that have no free register.

Trap one: a count of zero runs 256 times

Suppose the number of iterations comes from a variable, and the variable is 0. The loop above decrements first and tests afterward, so X goes from 0 to $FF and the body runs 256 times. A countdown loop cannot do "zero iterations" unless you test first:

guard.sasm
        LDX count
        BEQ skip            ; zero iterations: jump over the loop
loop:   ; body
        DEX
        BNE loop
skip:

The LDX sets Z from the loaded value, so BEQ can test it with no compare. This guard costs two instructions and prevents the most common counted-loop bug.

Trap two: using the index in the body

If the body needs the loop index, the order of values matters. A loop on X from 5 down to 1 uses indexes 5, 4, 3, 2, 1, and a table of five bytes needs table-1,X to line up with element 0. That works, but it is the kind of off-by-one that confuses readers. The alternative is to count down through zero and stop on the sign:

signloop.sasm
        LDX #$0F            ; X runs 15 down to 0: 16 iterations
loop:   STA $0300,X         ; natural indexing: table[X]
        DEX
        BPL loop            ; continue while X is positive or zero

BPL branches when N is clear, and DEX from 0 gives $FF, which sets N. So the loop runs for X = 15, 14, ..., 0 and exits when X wraps to $FF. Because N only means "negative" for values up to 127, this trick works for counts up to 128 iterations. Above that, X = $80 would look negative immediately and the loop would exit at once.

Loop endValues of X in the bodyIterations for start value nLimit on n
DEX, BNEn down to 1n (256 when n is 0)256
DEX, BPLn down to 0n + 1127
INX, CPX #limit, BNE0 up to limit - 1limit255
INX, BNEstart up to 255256 - start256

Trap three: the compare clobbers the carry

An up-counting loop uses CPX, and CPX sets the carry. If the body is an addition that must pass its carry from one iteration to the next, as in a multi-byte add, the compare destroys it:

carrybug.sasm
        LDX #$00
        CLC
loop:   LDA num1,X
        ADC num2,X          ; wants the carry from the previous byte
        STA sum,X
        INX
        CPX #$08            ; BUG: this overwrites C
        BNE loop

This adds two 8-byte numbers, least significant byte first. After the first byte INX leaves the carry alone, but CPX #$08 then sets it from the comparison: X is below 8, so the carry comes out clear on every pass. The carry out of each byte is thrown away, and the sum is right only when no byte overflows. The bug is intermittent, which makes it nasty: small test numbers pass.

The classic fix keeps the carry alive by ending on INX and BNE alone. The index starts at $F8, eight below the wrap point, and each address is written as the table start minus $F8, so the first pass lands on byte 0:

carryfix.sasm
        LDX #$F8            ; eight increments from wrapping to $00
        CLC
loop:   LDA num1-$F8,X      ; X = $F8 reads num1, X = $FF reads num1+7
        ADC num2-$F8,X
        STA sum-$F8,X
        INX                 ; INX leaves the carry alone
        BNE loop            ; X wraps to $00 after 8 passes

Indexed addressing adds X as an unsigned byte, so with X = $F8 the address num1-$F8,X is num1 exactly, and the eighth pass reads num1+7. X reaches zero after eight increments, which sets Z and ends the loop. No compare ran, so the carry survived every pass. The trick needs the tables above the first page, so that the subtraction in the operand stays a valid address. The alternative that works anywhere is PHP before the compare and PLP after it, at a cost of 7 cycles per iteration.

Counts above 255

An 8-bit register counts to 255, so a 1,000-iteration loop needs two counters. The usual form is nested loops, with the inner loop running a full 256 times:

nested.sasm
        LDY #$04            ; outer count: 4 x 256 = 1,024 iterations
outer:  LDX #$00            ; inner: 0 wraps to 256 iterations
inner:  ; body
        DEX
        BNE inner
        DEY
        BNE outer

That runs the body 1,024 times. Setting X to zero and relying on the wrap is the cheapest way to get 256, and a deliberate use of the "trap one" behavior. For an exact count that is not a multiple of 256, count with a 16-bit variable in zero page:

count16.sasm
count   = $10               ; 16-bit counter, low byte first

        LDA #<1000
        STA count
        LDA #>1000
        STA count+1
loop:   ; body
        LDA count
        BNE lowdec          ; low byte not zero: no borrow
        DEC count+1         ; low byte is zero: borrow from the high byte
lowdec: DEC count
        LDA count
        ORA count+1         ; Z = 1 only if both bytes are zero
        BNE loop

The borrow logic is the part to study. Before decrementing the low byte, test whether it is zero: if so, the decrement will wrap to $FF and the high byte must go down too. The final ORA combines both bytes, so Z is set only when the whole 16-bit value is zero.

Counting cycles

The 6502 has exact timings, so a loop's duration is arithmetic. From the programming manual: DEX takes 2 cycles, and BNE takes 2 cycles when not taken, 3 when taken, plus 1 more if the branch crosses a page boundary. For a loop that is just DEX and BNE, each full pass costs 5 cycles and the last pass costs 4:

Iterations nCycles for the loop alone
14
29
1049
n5n - 1

Add 2 cycles for the LDX #n before it. A delay of exactly 49 + 2 = 51 cycles is LDX #10 with an empty DEX, BNE loop, provided the branch does not cross a page, which would add a cycle per taken branch. The result matters on machines where code must line up with the video beam, and this is why programmers align hot loops to avoid page crossings. The rule of thumb is that the per-iteration cost is the sum of the body's cycles and 5, and the last iteration is one cycle cheaper.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.