PBASIC Programming/Branches

Comparison Operators
A computer processor, such as the BasicStamp is capable of comparing two numbers and testing their relationship. The BasicStamp can compare two numbers and determine if they are equal, not equal, greater than, or less than. We can use special comparison operators to ask the BasicStamp to compare numbers.


 * Equal:To determine if two numbers are equal, we use the "=" operator.
 * Not Equal: To determine if two numbers are not equal, we use the "<>" operator.
 * Greater Than: To determine if one number is greater than the other, we use the ">" operator.
 * Greater Than or Equal:To determine if one number is greater than or equal to another number, we use the ">=" operator.
 * Less Than: We can use the "<" operator to determine if one number is less than the other.
 * Less Than or Equal:We can use the "<=" operator to determine if one number is less than or equal to another number.

IF / THEN Branches
Once we compare two numbers, we can ask the BasicStamp to take action depending on that comparison. Using the IF / THEN structure, we can perform a jump if the condition is true, and we will not jump if the condition is false. The format of the instruction is:

IF [Condition] THEN [Label]

Where [Condition is a comparison of two values (two variables or a variable and a constant, for instance). If the comparison is true, then the control flow jumps to the [Label].

IF / THEN / Else Structures
Sometimes we want to have a second option. for instance, we want to do one thing if the comparison is true, and we want to do a different thing if the comparison is false. Here is an example, using a single IF / THEN branch, and GOTOs:

IF [Condition] THEN GoTrue ... 'Do this if the condition is false GOTO EndBranch GoTrue: ... 'Do this if the condition is true GOTO EndBranch EndBranch:

Only one set of code in this case will be executed, depending on whether the condition is true or false. There are other ways to arrange this, of course.

Simple Loops
We can use GOTO to create a simple infinite loop. The program will repeat the code in the middle of the loop forver:

LoopTop: ... 'Do this infinitely GOTO LoopTop

We can use IF / THEN branches to create more advanced loops as well. However, most of the advanced loops that we can create can be made in a better way. We will discuss more advanced loops in the next chapter.