Propeller Manual

Table Of Contents
2: Spin Language Reference – IF
!outa[1] 'Toggle P1
Here, if X is greater than 100, I/O pin 0 is toggled, otherwise, if X equals 90, I/O pin 1 is
toggled, and if neither of those conditions were true, neither P0 nor P1 is toggled. This is a
slightly shorter way of writing the following code:
if X > 100 'If X is greater than 100
!outa[0] 'Toggle P0
else 'Otherwise,
if X == 90 'If X = 90
!outa[1] 'Toggle P1
Both of these examples perform the same actions, but the first is shorter and is usually
considered easier to read. Note that the
ELSEIF, just like the ELSE, must be lined up (start in
the same column) as the
IF that it is associated with.
Each
IF conditional statement can have zero or more ELSEIF statements associated with it.
Look at the following:
if X > 100 'If X is greater than 100
!outa[0] 'Toggle P0
elseif X == 90 'Else If X = 90
!outa[1] 'Toggle P1
elseif X > 50 'Else If X > 50
!outa[2] 'Toggle P2
We have three conditions and three possible actions here. Just like the previous example, if X
is greater than 100, P0 is toggled, otherwise, if
X equals 90, P1 is toggled, but if neither of
those conditions were true and
X is greater than 50, P2 is toggled. If none of those conditions
were true, then none of those actions would occur.
There is an important concept to note about this example. If
X is 101 or higher, P0 is toggled,
or if
X is 90, P1 is toggled, or if X is 51 to 89, or 91 to 100, P2 is toggled. This is because the
IF and ELSEIF conditions are tested, one at a time, in the order they are listed and only the
first condition that is true has its block of code executed; no further conditions are tested after
that. This means that if we had rearranged the two
ELSEIFs so that the “X > 50” were checked
first, we’d have a bug in our code.
Propeller Manual v1.1 · Page 115