![]() |
You. Forth. Simplicity. |
reload node | edit | recent changes | front page
Simply moving numbers around on a stack can be a lot of fun. Eventually, however, you'll want to do something useful with them. This section describes how to perform arithmetic operations in Forth.
The first thing you should know is that RetroForth can be extended to recognize many kinds of numbers, but only recognizes one kind of numbers initially: single. A single is any value that can fit in the native cell size, which is 32 bits. In other words, a single can be any value from 0 through roughly 4 billion.
One thing you should know is that RetroForth doesn't care about signedness. In other words, treating the value on the stack as "-1" rather than "4294967295" depends on the word you apply to it; the value itself has no intrinsic value to RetroForth. This also means that a "character" can be dealt with as a number (the ASCII code corresponding to the character) without doing any 'conversion' on the value first. This is a strong point of Forth, but it also puts the onus for "doing the right thing" on the programmer.
Forth arithmetic operators work on the numbers currently on top of the stack. If you want to add the top two numbers together, use the Forth word +, pronounced plus. Enter:
2 3 + .
2 3 + 10 + .
This style of expressing arithmetic operations is called Reverse Polish Notation, or RPN. It will already be familiar to those of you with HP calculators. In the following examples, I have put the algebraic equivalent representation in a comment.
Some other arithmetic operators are - * /. Enter:
30 5 - . ( 25 = 30 - 5 )
30 5 / . ( 6 = 30 / 5 )
30 5 * . ( 150 = 30 * 5 )
30 5 + 7 / . ( 5 = (30 + 5) 7 )
An important fact to keep in mind is that when you are doing division with integers using , the remainder is lost. Enter:
15 5 / .
17 5 / .
This is true in all languages on all computers. Later we will examine /mod and mod which do give the remainder.