Comparing and branching

FlashForth lets you compare two numbers on the stack, using the relational operators >, < and =.
2 3 =  ok<$,ram>0 
2 3 >  ok<$,ram>0 0 
2 3 <  ok<$,ram>0 0 ffff 
. -1  ok<$,ram>0 0
These operators consume both arguments and leave a flag, to represent the boolean result. Above, we see that ``2 is equal to 3'' is false (value 0), ``2 is greater than 3'' is also false, while ``2 is less than 3'' is true. The true flag has all bits set to 1, hence the 16-bit hexadecimal representation ffff and the corresponding signed representation -1. FlashForth also provides the relational operators 0= and 0< which test if the TOS is zero and negative, respectively.


The relational words are used for branching and control. For example,

: test 0= invert if cr ." Not zero!" then ;  ok<$,ram>
0 test  ok<$,ram>
-14 test 
Not zero! ok<$,ram>
The TOS is compared with zero and the invert operator (ones complement) flips all of the bits in the resulting flag. If TOS is nonzero, the word if consumes the flag and executes all of the words between itself and the terminating then. If TOS is zero, execution jumps to the word following the then. The word cr issues a carriage return (newline).


The word else can be used to provide an alternate path of execution as shown here.

: truth 0= if ." false" else ." true" then ;  ok<$,ram>
1 truth true ok<$,ram>
0 truth false ok<$,ram>
A nonzero TOS causes words between the if and else to be executed, and the words between else and then to be skipped. A zero value produces the opposite behaviour.


Peter Jacobs 2013-06-12