Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What methods for using control flow are there in 6502?

I am trying to understand control flow in 6502 assembly.

Say I have the following code:

    ControlFlow:
      lda mem
      cmp #1
      bne .sub_one

      cmp #2
      bne .sub_two

      .sub_one:
        ; sub routine one goes here
        jmp .done ; <-------------- without this jmp, .sub_two will execute

      .sub_two:
       ; sub routine two goes here

      .done:

      rts

Personally, I would love a switch statement or some other control flow structure. The JMP above concerns me as well. It seems like there is a better way to handle multiple cases without this type of spaghetti code.

like image 432
JohnnyStarr Avatar asked Dec 07 '22 09:12

JohnnyStarr


1 Answers

Jump tables can be useful, if the number of cases is large enough. On the left, there's a template (untested) for jump to label that pushes the correct address to stack and returns. On the right there's a diff to jsr based routine, that will continue at the label _out: after returning from each subroutine. The carry logic is inverted on 6502, meaning that carry will be set if (Acc >= Imm).

; goto  label[n]   vs.         call label[n]

lda variable
cmp #MAX_PLUS_ONE                          
bcs _out
tax
lda table_hi, X
pha                vs.         sta jsrcmd+2
lda table_lo, X
pha                vs.         sta jsrcmd+1
rts                vs. jsrcmd: jsr 1000        ; self modify

_out:  
like image 139
Aki Suihkonen Avatar answered Dec 28 '22 12:12

Aki Suihkonen