Control Words and Loops

The main control word in forth is if, which pops the top item off the stack and, if it does not equal zero, continues executing the code. If it does equal zero, the execution will jump to the corresponding else or then word. This works pretty much the same as if statements work in most imperative langauges.

2 1 > if
"2 is, in fact greater than 1\n" puts
"... That doesn't seem right\n" puts

There are three main ways to do something repeatedly in forth, and I'll cover all of them here.

Do Loops

Do loops are perfect for when some code should be executed a certain number of times. They are comparable to iterating over a range in python. The do word takes the starting index and the limit of the loop on the stack and runs the code up to loop, then increments the index by one every time. You can access the current index using i. Here's an example

10 0 do
"Current index is " puts
i @ . endl

This will print the numbers from 0 through 9 to the screen. It will not print 10.

While Loops

Another way to iterate in forth is using a while loop. These loops are good for when you want to execute some code until something happens. They work a lot like while statements in other languages. The following is an example of a while loop in C that runs while a variable c is greater than 3

int c = 6;
while (c > 3)
printf("%d\n", c);

The equivalent in forth would be

variable c
c @ 3 >
c . endl
c @ 1 + c !


As with (almost) any language, recursion is also an option, although not widely used in Forth. You can figure out how to do this yourself, it's not that hard.

ForthC supports some tail-call optimization so recursion should be fairly fast.