简体   繁体   中英

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#index-TO_0028--value-_0022name_0022-_002d_002d--_0029-core_002dext

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 . 

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 @ . 

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 @ . 

if you define a word as 5 value A

when you type A

you get 5 put on the stack

when you type variable A

when you type A

you get an address put on the stack

to get the value inside, you use @

to write to it, you use !

value creates a word that puts a value on the stack

variable creates a word that puts an address on the stack

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM