if ... else
Forth has if ... else ... like other languages, but the structure is quite different from that which you are used to. if treats the topmost stack entry as a boolean. Any nonzero value is considered as true. Here is some sample code that shows you how to use if:
: is_it_true
if
." That is true"
cr
else
." Not true"
cr
then
;Note that the if statement is terminated by then. This is somewhat counterintuitive if you're used to other programming languages. To show how this new word works, if we typed:
5 is_it_true
we'd get:
That is true
but, if we typed:
0 is_it_true
we'd then get:
Not true
For a simple if statement with no need of else, the format is simply:
: is_it_true
if
." That is true"
cr
then
;Now, rather than using then to end the if structure, you can also use endif:
: is_it_true
if
." That is true"
cr
endif
;
then and endif work in exactly the same way. Using endif rather than then makes code a little easier to read. Which code structure you use is up to you.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access