You have some typos:
- Your branch instruction is testing
$t0
, but the target of the slt
is $t1
so that is a mismatch.
- You have a conditional branch instruction with a label, but don't define the label.
- Your label name is
endLoop
, but this is just an if
, not a while
or other loop condition, and the the statement controlled by the if
isn't a break
.
Otherwise looks like you have the right idea. But this is tricky stuff to get right.
To be clear, you are aware that we have to reverse (negate re: boolean logic) the sense of the condition for assembly language's if-goto style, as compared with structured programming's if-then construct.
if (t4 >= t5)
t8++;
becomes
if (t4 < t5) goto skip; // !(a >= b) ---> a < b
t8++;
skip: ;
Now, I would have written the above more directly in assembly:
slt $t1, $t4 $t5 # let's see if t4 < t5
bne $t1, $zero, skip # yes? goto skip
addi $t8,$t8,1
skip:
Instead you have reversed the operands $t4
and $t5
, and then also reversed the branch condition: beq
vs. my bne
. This is very close to a triple negation of the (structured style) C (and this would have worked), but there is a subtle difference.
So, what you have written is:
if (!(t5 < t4)) goto skip;
t8++;
skip: ;
which — translated to structure programming — is:
if (t5 < t4) // logically: remove the negation and incorporate then
t8++;
and we can see that if we reverse the operands but also switch the relation, we have:
if (t4 > t5) // same exact logical condition as immediately above
t8++;
So, your code does not produce the same condition test as the C code, since the operation under equality is different from the original.
You assembly code is doing t4 > t5
, and the C code is doing t4 >= t5
. See the difference?
This stuff is tricky because:
- We have to reverse (negate) the condition when going between structured statement and if-goto style, and,
- MIPS provides only one of the ordered relational operations (it has
<
but not <=
, >
, >=
), and so, that means when we need what would have been sge
we have to simulate it (via slt
by reversing operands and/or reversing the branch on true vs. branch false).
Related: