assembly6502retro-computing

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.


Solution

  • There is no better way actually but there might be an improvement like calling the FlowControl as a subroutine and returning with RTS.

    This is the main flow.

      jsr ControlFlow
      ; main routine continues here
    

    Here is the sub routine.

    ControlFlow:
      lda mem
      cmp #1
      bne .sub_one
      cmp #2
      bne .sub_two
      cmp #3
      bne .sub_three
        ; case else here
      rts
    
      .sub_one:
        ; sub routine one goes here
      rts
    
      .sub_two:
       ; sub routine two goes here
      rts
    
      .sub_three:
       ; sub routine three goes here
      rts
    

    if sub routines are too long, you need to use JMPs as mentioned before.

    .jump_to_sub_one
      jmp .sub_one
    .jump_to_sub_two
      jmp .sub_two
    .jump_to_sub_three
      jmp .sub_three
    
    ControlFlow:
      lda mem
      cmp #1
      bne .jump_to_sub_one
      cmp #2
      bne .jump_to_sub_two
      cmp #3
      bne .jump_to_sub_three
        ; case else here
      rts
    
      .sub_one:
        ; sub routine one goes here
      rts
    
      .sub_two:
       ; sub routine two goes here
      rts
    
      .sub_three:
       ; sub routine three goes here
      rts
    

    That's how it is done and unfortunately, there is no better way. This applies to many assembly languages if not all.