Branching Overview

To do branching in assembly, we use the bne and beq instructions. Setting these up can be a bit confusing because you have to think of the logic in reverse compared to how you normally think about if statements.

When writing an if-else statement. You might usually think of it as…

if (this statement) is true, then do the following code!
   // the following code …

but when writing bne and beq instructions, you have to think of it like

if (this statement) is true, then SKIP the following code!
   // the following code …

Both instructions have the general form: beq/bne reg1, reg2, label

beq (branch-equal) will jump to the line of code referenced by label, only if reg1 == reg2.

bne (branch-not-equal) will jump only if reg1 != reg2.

If block

 		# C code:
 		#   if (x == y) {
		#	    // ... do something
		#   }
		#   // ... do more stuff
		#
		# Since we want to run the code inside the if block only if x == y, we need to skip it if x != y
		#
		# Registers:
		# x			$t0
		# y			$t1

		bne $t0, $t1, DONE  # if (x != y) goto DONE 
		#  ... do something

DONE:
		# ... do more stuff

Note how our original C code was checking if x == y, since that tells us whether to DO the code inside the if-block.

But in MIPS we switched to checking if x != y, because that tells us if we need to SKIP the code inside the if-block.

if-else block

For an if-else block. The important thing is that we need to include an extra jump inside the “if” section, to make sure that the code inside the “else” section is skipped. This way, either the “if” section is run, or the “else” section, but never both.

 		# C code:
 		#   if (x == y) {
		#	    // ... do something
		#   }
		#   else {
		#     // ... do something else
		#   }
		#   // ... do more stuff
		#
		# Assume $t0 = x, $t1 = y
		
		
		bne $t0, $t1, ELSE  # if (x != y) goto ELSE
		# ... do something
		j DONE              # goto DONE (this skips the ELSE code)
		
ELSE:
		# ... do something else
		# we don't need to jump here, since the DONE code is the next thing anyways
		
DONE:
		# ... do more stuff

SLT

The set-less-than instruction (slt) has the form: slt destination, input1, input2.

The instruction checks if input1 is less than input2. if TRUE, then it sets destination to 1. if FALSE, it sets destination to 0.

slt is commonly used along with beq / bne, like so: