0

In lecture, our professor said that there is a reason behind using bne in branching rather than using beq(and left us to figure it out), like the example shown below.

if ( i == j )
    i++ ;
j-- ;

which compiles down to

bne  $r1, $r2, L1        # branch if ! ( i == j ) 
addi $r1, $r1, 1         # i++ 
L1: addi $r2, $r2, -1    # j-- 

Also, in this link, it is also being implied that it is a convention in MIPS assembly to implement conditional branching in negation manner. My best bet was, it was for keeping the common case simple - and therefore fast-, because intuitively if we were checking for equality then we would expect it to be more likely to become equal, and therefore PC to branch when it is not equal. I think I just pushed hard to make it reasonable, but I still couldn't distinguish the core difference between implementing it in beq or in bne. I would really appreciate if someone explains why.

Jonas
  • 121,568
  • 97
  • 310
  • 388
Burak.
  • 598
  • 7
  • 19

1 Answers1

3

Consider what the code would look like if you had used beq. You might end up with this:

beq $r1, $r2, L1
L2: addi $r2, $r2, -1 # j--
...
...
L1: addi $r1, $r1, 1 #i++
j L2

Or this:

beq $r1, $r2, L1
addi $r2, $r2, -1 # j--
j L2
L1: addi $r1, $r1, 1 #i++
addi $r2, $r2, -1 # j--
L2:

In either case you'd have an extra branch in one of the execution paths, compared to if you had used bne at the beginning.

Michael
  • 57,169
  • 9
  • 80
  • 125
  • Aha I think the problem not only putting a branch but is writing one more instruction to fulfill the overall functionality. – Burak. Jan 21 '16 at 12:49
  • Which may be not a preferred because takes much space in instruction memory. However I wonder, what if we were using if-else ? It uses again the same negation pattern even though, I believe, we necessarily don't need to. – Burak. Jan 21 '16 at 12:57