<< Home | About Forth | About TurboForth | Download | Language Reference | Resources | Tutorials | YouTube >>


2 Colon Definitions

2.1 What are Colon Definitions?

Colon definitions are used to make your own words in Forth. Normally, in Forth, when we type something at the keyboard, it is executed immediately. Like this:

  9 8 * .

The above code is executed immediately. It puts 9 on the stack, then it puts 8 on the stack. Then * (multiply) executes, which multiplies the top two values on the stack, and leaves the result on the stack. Then . executes, which removes the result from the stack, and displays it.

Notice how short and exact the code is? In other languages, such as C you might have to write:

  void main(void)
  {
    printf("%d",9*8);
  } 

Then you would have to compile it, link it, then execute it.

Clearly though, sometimes you want code to be stored away for later execution. This is where the colon definition is used in Forth. Here is a simple colon definition:

  : DOUBLE DUP + ;

Notice the colon at the beginning (hence the name 'colon definition')? Following the colon is a word. This is the name of our word. We are creating a new word called DOUBLE. Next, we put the executable code that makes up the executable part of our word DOUBLE. In this case, DUP + .. Finally, the ; (semi-colon) is used to indicate the end of the word.

Notice that nothing really happened when you pressed enter? Instead of executing the code, the code was stored away, to be executed later. At this point, the Forth language has been 'extended'. We have 'taught' Forth a new word: DOUBLE. As written, DOUBLE will double any number that is on the stack when we execute it. How do we execute it? By typing its name! In this case, DOUBLE needs some data on the stack to work with. So, let's put some data on the stack and call DOUBLE:

  99 DOUBLE

TurboForth responds with ok:1 showing us that there is one data item on the stack. We can use the word . (dot) to display it, which also removes it:

  .

And TurboForth responds with:

  198 ok:0

99+99=108. Congratulations. You just wrote your first Forth program!

Forth programs are written in this way. A colon definition references other (already existing) words. In this way, programs are built up incrementally, 'standing on their predecessors shoulders' in small steps, and can be tested at each step of the way.

<-- Back to Tutorials


You may be wondering how DOUBLE works? Well, first, we put a number on the stack (in our example, 99). When DOUBLE is called (by typing its name) it executes DUP ("duplicate") which duplicates the top number on the stack. So now the stack contains 99 and 99. Then + executes. + removes the top two values from the stack, adds them together, and puts the result (we say "pushes the result") to the stack. Viola. The result is on the stack, waiting for us.


<< Home | About Forth | About TurboForth | Download | Language Reference | Resources | Tutorials | YouTube >>