Conditionals - IF ELSE THEN CASE
You will now use the TRUE and FALSE flags you learned to generate in the last
section. The "flow of control" words accept flags from the stack, and then
possibly "branch" depending on the value. Enter the following code.
A D V E R T I S E M E N T
: .L ( flag -- , print logical value )
IF ." True value on stack!"
ELSE ." False value on stack!"
23 7 < .L
You can see that when a TRUE was on the stack, the first part got executed. If a
FALSE was on the stack, then the first part was skipped, and the second part was
executed. One thing you will find interesting is that if you enter:
the value on the stack will be treated as true. The flow of control words
consider any value that does not equal zero to be TRUE.
The ELSE word is optional in the IF...THEN construct. Try the
: BIGBUCKS? ( amount -- )
IF ." That's TOO expensive!"
Many Forths also support a CASE statement similar to switch() in 'C'.
: TESTCASE ( N -- , respond appropriately )
0 OF ." Just a zero!" ENDOF
1 OF ." All is ONE!" ENDOF
2 OF WORDS ENDOF
DUP . ." Invalid Input!"