Search code examples
easy68k

Easy68K IF-ELSE branching


writing my first assembly language program for class using Easy68K.

I'm using an if-else branching to replicate the code:

IF (P > 12)
    P = P * 8 + 3
ELSE
    P = P - Q

PRINT P

But I think I have my branches wrong because without the first halt in my code the program runs through the IF branch anyway even after the CMP finds a case that P < 12. Am I missing something here or would this be a generally accepted way of doing this?

Here is my assembly code:

START:  ORG     $1000       ; Program starts at loc $1000

        MOVE    P, D1       ; [D1] <- P
        MOVE    Q, D2       ; [D2] <- Q

* Program code here

        CMP     #12, D1     ; is P > 12?
        BGT     IF          ;
        SUB     D2, D1      ; P = P - Q

        MOVE    #3, D0      ; assign read command
        TRAP    #15         ;
        SIMHALT             ; halt simulator


IF      ASL     #3, D1      ; P = P * 8 
        ADD     #3, D1      ; P = P + 3
ENDIF

        MOVE    #3, D0      ; assign read command
        TRAP    #15         ;
        SIMHALT             ; halt simulator

* Data and Variables

        ORG     $2000       ; Data starts at loc $2000

P       DC.W    5           ;
Q       DC.W    7           ;

        END    START        ; last line of source

Solution

  • To do if..else, you need two jumps; one at the start, and one at the end of the first block.

    While it doesn't affect correctness, it is also conventional to retain source order, which means negating the condition.

        MOVE    P, D1       ; [D1] <- P
        MOVE    Q, D2       ; [D2] <- Q
    
    * Program code here
    
        CMP     #12, D1     ; is P > 12?
        BLE     ELSE        ; P is <= 12
    
    IF
        ASL     #3, D1      ; P = P * 8 
        ADD     #3, D1      ; P = P + 3
        BRA     ENDIF
    
    ELSE
        SUB     D2, D1      ; P = P - Q
    ENDIF
    
    
        MOVE    #3, D0      ; assign read command
        TRAP    #15         ;
        SIMHALT             ; halt simulator