forth

How is a Forth value different from a variable?


Reading the Gforth manual, a value can be changed using the word TO, so how is it different than a variable?

https://gforth.org/manual/Values.html


Solution

  • VALUE takes an initial value, and the created word puts the value directly on the stack like CONSTANT. The value can still be changed using TO. Word definitions in many Forths using VALUE's will be smaller, because they just need to reference the created word and not !.

    5 VALUE TERRYS
    TERRYS . 5 ok

    VARIABLE just reserves space for the value, uninitialised, and the created word puts the address of the variable on the stack instead.

    VARIABLE TERRYS
    5 TERRYS !
    TERRYS @ . 5 ok

    VARIABLE is useful when you want to take the address of the variable, and VALUE is useful when you don't need to.

    If you want to initialise the variable, and be able to take the address, it is actually easier to just use CREATE and ,, like so:

    CREATE TERRYS 5 ,
    TERRYS @ . 5 ok