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.
1
2 1 > if
2
"2 is, in fact greater than 1\n" puts
3
else
4
"... That doesn't seem right\n" puts
5
then
Copied!
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
1
10 0 do
2
"Current index is " puts
3
i @ . endl
4
loop
Copied!
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
1
int c = 6;
2
while (c > 3)
3
{
4
printf("%d\n", c);
5
}
Copied!
The equivalent in forth would be
1
variable c
2
begin
3
c @ 3 >
4
while
5
c . endl
6
c @ 1 + c !
7
repeat
Copied!

Recursion

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.
​
Last modified 1yr ago