Difference between add and addu
Solution 1:
The instruction names are misleading. Use addu
for both signed and unsigned operands, if you do not want a trap on overflow.
Use add
if you need a trap on overflow for some reason. Most languages do not want a trap on signed overflow, so add
is rarely useful.
Solution 2:
If you are using signed numbers, you should use add
if you want a trap to be generated when the result overflows.
If you are using unsigned numbers, you should always use addu
and check the overflow of the addition by comparing the result with either numbers (if the result is less than the operands then the addition did overflow).
Here goes a snippet to show how you would check for overflow in unsigned addition:
li $a1, 0xFFFF0FFF
li $a2, 0x00010000
addu $a3, $a1, $a2 # This unsigned addition overflows (set $a3 to $a1+$a2)
bgt $a1, $a3, overflowed
bgt $a1, $a2, overflowed
# If you get here, unsigned addition did not overflow
# your code goes here...
overflowed:
# If you get here, unsigned addition overflowed
# your code goes here...
Solution 3:
OVERFLOW is NOT as declared in the question, this carry bit is NOT an overflow bit, in the given example there is NO OVERFLOW, overflow is when:
MSB1 = 1 && MSB2 = 1 && MSBofRESULT = 0
OR
MSB1 = 0 && MSB2 = 0 && MSBofRESULT = 1
so stick with add
it will flag overflow, and the carry bit in your example (which is not an overflow) will not bother you. addu
does the same except no exception is ever raised.