Autres articles / Other articles

Part 3 - Comparaisons et branchements

published: 7 February 2023 / updated 7 February 2023

Lire cette page en français

 

 

Comparing and branching

FlashForth lets you compare two numbers on the stack, using the relational operators >, < and =.

hex 
2 3 = .     \ display: 0 
2 3 >       \ display: 0 
2 3 <       \ display: ffff 

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  
  ; 
0 test      \ no display 
-14 test    \ display: Not zero! 

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  
  ;  
1 truth     \ display: true 
0 truth     \ display: false 

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.

Boolean operators

The FORTH language does not manage any type of data other than integers processed by the parameter stack.

Integers in the FlashForth version are in 16-bit format. There is therefore no boolean type in Forth, a fortiori with FlashForth.

FlashForth has two predefined constants, false and true, which can be respectively treated as boolean values:

decimal 
false .     \ display 0 
true  .     \ display -1