Skip to main content
Engineering LibreTexts

7.3: if-else Statements

  • Page ID
    27136
  • A more useful version of the if statement also allows for the false condition, or a if-else statement. If the condition is true, the first block is executed, otherwise the second block is executed. A simple code fragment that illustrates this point is shown below.

    if (($s0 > 0) == 0) 
    {
          print("Number is positive")
    }
    else
    {
          print("Number is negative")
    
    }
    

    This is a modification to logic in Program 7.1. This code will print if the number is positive or negative. The purpose here is to show how to translate an if-else statement from pseudo code to assembly language. The translation of the if-else statement occurs using the following steps.

    1. Implement the conditional part of the statement as in program 7.1.
    2. Add two labels to the program, one for the else and one for the end of the if. The beqz should be inserted after the evaluation of the condition to branch to the else label. When you have completed step 2, you will have code that looks similar to the following:
    3. At the end of the if block, branch around the else block by using an unconditional branch statement to the endif. You now have the basic structure of the if statement, and you code should like the following assembly code fragment.
      Program 7-4: Assembly code fragement for an if-else statement
      
      lw $t0, num
      sgt $t1, $t0, $zero
      beqz $t1, else
      #if block
          b end_if
      #else block
      else:
      end_if:
      
    4. Once the structure of the if-else statement is in place, you should put the code for the block into the structure. This completes the if-else statement translation. This is the following program.
      Program 7-5: if-else program example
      
      .text
          lw $t0, num
          sgt $t1, $t0, $zero
          beqz $t1, else
              #if block
              la $a0, PositiveNumber
              jal PrintString
              b end_if
              #else block
          else:
              la $a0, NegativeNumber
              jal PrintString
          end_if:
          jal Exit
      .data
          num: .word -5
          PositiveNumber: .asciiz "Number is positive"
          NegativeNumber: .asciiz "Number is negative"
      .include "utils.asm"
    • Was this article helpful?