If Statements - Branches Part I
Posted on 10-17-2006, by Tim
To perform an if statement in LC-3, you should use the branch instruction (BR). There are three flags you can pass to it (n, z, and p). The main difference between BR and higher-level languages' if statements is that if statements compare two numbers, while BR compares one number to see if it is negative (n), zero (z) and/or positive (p). (Note: the nzp flags must be entered in order. For example, using zn is correct, but zn is not.)

The statement directly before your BR instruction will be tested. Testing for all three nzp flags will always return true. If it is true, the branch will jump to a point in the program specified by you. For example:

ADD R1, R1, #1
; if the value is negative or zero, this code will by skipped
; this code will be executed for all values of R1, even negative values and zero

Remember: only the last statement executed before the branch will be evaluated for nzp.
Difficulty: Intermediate - Views: 37501

User Comments
Adrian wrote:
Real quick, if you want to do the construct:

if (a == b)
  //do something1
  //do something2

all you need is the following LC-3 construct:

//variable 'a' is in R1
//variable 'b' is in R2
//subtract a from b, if it is 0 they are equal
NOT R0, R2 //negate R2 and store it in R0
ADD R0, R0, #1
ADD R0, R1, R0 //subtract a from b
BRnp ELSE //if they arent 0, we go to the else block
//do something1
BRnzp END //we did something1, so we need to skip the else block
//do something2

Copyright 2006 © LC3Help.com v1.4.7