If else in MIPS

前端 未结 3 1228
盖世英雄少女心
盖世英雄少女心 2021-01-29 04:38

I am learning MIPS programming, in which I am trying to implement If else conditions. But the problem is when I enter 2 to select subtract condition, the program doesn\'t work.

3条回答
  •  离开以前
    2021-01-29 04:55

    If you are going to use branch on equals then your program should actually perform some branch that makes sense. Examine your branch instruction:

        beq $s0,$t0,ADDTN
    ADDTN:
    

    In MIPS you must remember that the PC (program counter) will simply advance line by line unless directed otherwise. A branch instruction can direct the PC to some other location in the program; however, in your code the branch instructions tell the PC to just advance to the next line which is exactly what the program would do without a branch instruction.

    Also, if you only want these certain labels, ADDTN, SUBTN, to be executed, then each label must have a jump instruction at the end of its operation. For example, when ADDTN is finished the program should jump past SUBTN, unless of course you want SUBTN to also execute. Here is an example of what you could do. Have a series of branch instructions which divert the PC to specific operator labels and at the end of each label jump to an EXIT label.

        beq $s0, $t1, SUBTN    # if(input==2) {goto SUBTN}
        beq $s0, $t0, ADDTN    # if(input==1) {goto ADDTN}
        beq $s0, $t2, MULT     # if(input==3) {goto MULT}
        beq $s0, $t3, DIV      # if(input==4) {goto DIV}
    
    
    ADDTN:
        # Code for addition
        j EXIT
    
    SUBTN:
        # Code for subtraction
        j EXIT
    
    MULT:
        # Code for multiplication
        j EXIT
    
    DIV:
        # Code for division
        j EXIT
    
    EXIT:
        # Code to exit
        j EXIT
    

    Note: You should be able to visualize what will happen in this example if the value of $s0 is anything but 1, 2, 3, or 4. If none of the branch on equals causes the PC to jump to a label, then the program will execute the code in the ADDTN label. Also, if each label does not produce a jump to some ending label (EXIT) the program would continue executing the remaining labels.

    If you want to perform an explicit else statement, consider the following example:

    MAIN:    
        beq $s0, $t0, ADDTN    # if(input==2) {goto ADDTN}
        j SUBTN                # else {goto SUBTN}
    
    ADDTN:
        # Code for addition
        j EXIT
    
    SUBTN:
        # Code for subtraction
        j EXIT
    
    EXIT:
        # Exit the program
    

    In this example the first branch will check if the input correlates with the addition label. If it does, the PC will jump to that label; else if will advance to the next line which instructs a jump to the subtraction label.

提交回复
热议问题