If Statements - Branches Part I
Posted on 10-16-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:

Code:
ADD R1, R1, #1
BRp IS_POSITIVE
; if the value is negative or zero, this code will by skipped
IS_POSITIVE:
; 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: 24283

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

if (a == b)
{
  //do something1
}
else
{
  //do something2
}

all you need is the following LC-3 construct:
Code:

//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
ELSE:
//do something2
END:


Copyright 2006 © LC3Help.com v1.4.7