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

5 Variables

Forth has variables just like other languages. However, Forth tends to rely on them less than other languges, because the stack is available to carry information between words. That's the essence of Forth; using the stack to pass information around your program, such that variables are not required.

Variables in Forth are global; they can be accessed anywhere (an extension is available for TurboForth to provide local variables). They must be declared/defined before they can be used. Variables should be declared outside of a colon-definition.


5.1 Declaring Variables with VARIABLE

Variables should be declared outside of a colon definition, like this:


Here, the word VARIABLE makes a word in the Forth dictionary, called MyVar. Our variable is called MyVar.

Note: In TurboForth variables are automatically initialised to zero upon creation. Earlier dialects of Forth (e.g. FIG) required an initial value for variables. TurboForth does not require this.


5.2 Writing Values to Variables

It is important to understand that variables, once created, as shown above, become words in the dictionary, just like other words. Variables can be executed in Forth. When a variable is executed, it pushes its address (actually, the address of its storage area, or 'body'). We can use this address with the words ! (store) and @ (fetch) to read and write variables.

    123 MyVar !

The above stores the value 123 into the variable MyVar. Note that the value comes first, then the variable itself. The stack is then set up correctly for the word ! (store).


5.3 Reading Values from Variables

Reading from variables is also very simple. The word @ (fetch) is used to read a variables' contents. When one studies the stack requirements of the word @, one sees that it requires an address on the stack to 'fetch from'. Well, simply naming the variable is enough to cause it to push its address to the stack:

    MyVar @

Here, MyVar pushes its address to the stack, and @ reads the data at that address, leaving it on the stack (the address is removed by @). We can then display the value of the variable with a word like . (dot):

    MyVar @ .

<-- Back to Tutorials

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