MIPS assembly provides a variety of conditional and unconditional branch instructions.
Instructions Description
beq $t1, $t2, label # if ($t1 == $t2) goto label
bne $t1, $t2, label # if ($t1 != $t2) goto label
bgez $t1, label # if ($t1 >= 0) goto label
bgtz $t1, label # if ($t1 > 0) goto label
blez $t1, label # if ($t1 <= 0) goto label
bltz $t1, label # if ($t1 < 0) goto label
beqz $t1, label # if ($t1 == 0) goto label
bnez $t1, label # if ($t1 != 0) goto label
beq $t1, 123, label # if ($t1 == 123) goto label
bne $t1, 123, label # if ($t1 != 123) goto label
bge $t1, $t2, label # if ($t1 >= $t2) goto label
bgt $t1, $t2, label # if ($t1 > $t2) goto label
bge $t1, 123, label # if ($t1 >= 123) goto label
bgt $t1, 123, label # if ($t1 > 123) goto label
ble $1, $t2, label # if ($t1 <= $t2) goto label
blt $1, $t2, label # if ($t1 < $t2) goto label
j label goto label
Note:
A lot of branch instructions are pseudo-instructions. When translated into machine code, an
assembler uses $at ($1) as the middle register.
So don’t use $1 when using branch instructions.
EXAMPLES
Structure of an if-then-else statement
if (condition) {
then-block (execute if condition is true)
} else {
else-block (execute if condition is false)
}
Sketch of translation to assembly
(translation of condition, ending in branch to thenLabel)
(translation of else-block)
j endLabel
thenLabel:
(translation of then-block)
endLabel:
(rest of program)
EXAMPLE 1: if-then-else statement
# Pseudocode:
# if (a < (b + 3))
# a = a + 1
# else
# a = a + 2
# b = b + a
# Register mappings:
# a: $t0, b: $t1
addi $t2, $t1, 3 # tmp = b + 3
blt $t0, $t2, then # if (a < tmp)
addi $t0, $t0, 2 # (else case) a = a + 2
j end
then: addi $t0, $t0, 1 # (then case) a = a + 1
end: add $t1, $t1, $t0 # b = b + a
EXAMPLE 2: if-then statement
# Pseudocode:
# if (a < (b + 3))
# a = a + 1
# b = b + a
# Register mappings:
# a: $t0, b: $t1
addi $t2, $t1, 3 # tmp = b + 3
blt $t0, $t2, then # if (a < tmp)
j end
then: addi $t0, $t0, 1 # (then case) a = a + 1
end: add $t1, $t1, $t0 # b = b + a
EXERCISES
1. Write a program in MIPS assembly to find the largest number from three numbers.
Ask the user to input three numbers
Do the comparison
Print the largest number
2. Write a program which takes two numbers from user as input and performs operations on
those numbers as input from the user.
Print a message on console “Enter the first No”
Read the input integer from the console.
Print a message on console “Enter the second No”
Read the input integer from the console.
Print a message on console “Enter operation code: 1 for multiply, 2 for division, 3
for addition, 4 for subtraction”
Compute the result as per operation code.
Print the result on console “[Operation] between [first no] and [second no] results
in [result]”