# if.s - Illustrate what an if-then-else statement looks like # in the world of assembly. One subtlety: the sense of the # branch statement is reversed to how we would use it in a HLL. # In a HLL, when an "if" condition is true, we execute the code # that immediately follows. But in assembly, if your branch condition # is true, then you are able to jump ahead to avoid the code # that immediately follows. # Also - note the use of the $zero register, which always equals 0. .data prompt: .asciiz "Please enter an integer: " message_pos: .asciiz "Your number is at least zero.\n" message_neg: .asciiz "Your number is negative.\n" message_bye: .asciiz "Goodbye.\n" # Register use: # $s1 = the user's input .text main: li $v0, 4 # Ask for integer la $a0, prompt syscall li $v0, 5 # Put user's integer into $s1 syscall move $s1, $v0 # ------------------------------------------------------------------- # We begin with a branch instruction to allow us to skip ahead # to the "else" portion of the if-then-else. blt $s1, $zero, negative # Go to "negative" if s1 < 0 # ------------------------------------------------------------------- # If the branch condition is false, then we "fall through" to the # next instruction. This block of code is skipped if the blt # condition is true. li $v0, 4 # We know that s1 >= 0 la $a0, message_pos syscall j after_negative # Skip the negative part. # ------------------------------------------------------------------- # If the blt condition was true, we come down here. # Because of the j instruction above, this block of code is avoided # if we already executed the "then" portion. negative: li $v0, 4 # Destination of the branch la $a0, message_neg syscall # ------------------------------------------------------------------- # Having completed either the "then" or the "else" body, # we wind up here after the if-then-else statement. after_negative: li $v0, 4 la $a0, message_bye syscall li $v0, 10 # end of program syscall