if ... else
Like other programming languages, Forth has if ... else ... , but the structure is quite different to that with which you are used to. if treats the top-most stack entry as a boolean, and conditionally executes the code that follows. (Any non-zero value is considered as true.) then goes at the end of the code to be conditionally executed.
Here is some example code that shows you how to use if:
Here is some example code that shows you how to use if:
: test ( n -- , tests if n is true )
if
." That is true"
cr
else
." That’s not true"
cr
then
;
Note that the if statement is terminated by then. This is somewhat unusual if you’re used to other programming languages. To show how this new word works, if we typed:
5 test
we’d get That is true but, if we typed:
0 test
we’d then get That’s not true.
For a simple if statement with no need of else, the format is simply:
For a simple if statement with no need of else, the format is simply:
: true? ( n -- , prints if n is true )
if
." That is true"
cr
then
;
Now, let's learn how to create loops in Forth.