I’d love your help with the following problem.
I was asked to implement the function is_cube, which receives n as an argument and checks if it is a cube, in MIPS assembly. For example 8 (2^3) and 1000 (10^3) are cubes.
I wrote the following code:
# UNTITLED PROGRAM
.data
str: .asciiz "Please enter your number >"
str1: .asciiz "The number is a cube"
str2: .asciiz "The number is not a cube"
.text
main:
li $v0 4
la $a0 str
syscall
li $v0 5
syscall
move $t0 , $v0
li $t1, 0
blt $t0, $zero, negative
negative:
sub $t5, $zero, 1
mul $t0, $t0, $t5
is_cube:
addi $t1, $t1, 1
sgt $t2, $t1, $t0
bne $t2, $zero, There_is_not
mul $t3, $t1, $t1
mul $t4 ,$t3, $t1
beq $t4, $t0, There_is
jal is_cube
There_is:
li $v0 4
la $a0 str1
syscall
jal end
There_is_not:
li $v0 4
la $a0 str2
syscall
jal end
end:
and it works, without saving $s0 in a stack by $sp and all of this process. My question is: Is it Ok not saving it? and if so, When should I use it?
Thanks a lot.
You haven’t implemented a function. You have implemented a loop, which happens to use
jalinstead of a normal branch instruction. Execution starts in main and then falls through fromnegativeto a loop starting atis_cube, and then when the loop terminates atThere_isorThere_is_notyou usejal endinstead of another branch instruction.This code happens to work on MIPS because the
jalinstruction does not push the current value of the program counter to the stack, unlike the x86.If this is homework, you should go back to your notes on writing functions in assembler before submitting this code.