Page 1 of 1

Useful ARM code snippet for testing multiple conditions

Posted: Sun Feb 09, 2014 9:55 am
by colinh
You probably know the usual

Code: Select all

cmp      r0, #1
cmpne    r0, #2
beq      somewhere           // if (r0 == 1 || r0 == 2) {then ...}

// and

cmp     r0, #10
bge     somewhere
cmp     r0, #5
blt     elsewhere
here:                        // if (r0 >= 5 && r0 < 10) {then ...}
Here's a slightly more complicated one that I've found useful (you can leave out any of the actions, or have action 2 be exit, for example) :

Code: Select all

logic:
    cmp     r0, #0xA        // test 1
    movne   r2, #1
    moveq   r3, #1          // action 1
    movne   r3, #2          // action 2
    cmpne   r1, #0xB        // test 2
    rsbeqs  r2, #1
    addeq   r3, #0x30       // action 3
    addne   r3, #0x40       // action 4

// ne ne: r3 -> 42
// eq ne: r3 -> 31
// eq eq: r3 -> 41
// ne eq: r3 -> 32

// if (test1 is eq) {
//      action 1;
//      if (test2 is eq) {
//          action 4;
//      } else {
//          action 3;
//      }
//  } else {
//      action 2;
//      if (test2 is eq) {
//          action 3;
//      } else {
//          action 4;
//      }
//  }
The C-style pseudocode is supposed to show what it does. You might find it fun to see what your C compiler makes of it. With and without optimizations - but remember that for a proper comparison the compiler's not allowed to combine action<1|2> with action<3|4> (which it would do for r1 = 1 followed by r1 += 0x40, for example).