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!"
THEN
;
0 .L
FALSE .L
TRUE .L
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:
23 .L
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
following:
: BIGBUCKS? ( amount -- )
1000 >
IF ." That's TOO expensive!"
THEN
;
531 BIGBUCKS?
1021 BIGBUCKS?
Many Forths also support a CASE statement similar to switch() in 'C'.
Enter:
: TESTCASE ( N -- , respond appropriately )
CASE
0 OF ." Just a zero!" ENDOF
1 OF ." All is ONE!" ENDOF
2 OF WORDS ENDOF
DUP . ." Invalid Input!"
ENDCASE CR
;
0 TESTCASE
1 TESTCASE
5 TESTCASE
|