What does "local variable" mean in the Forth programming language?
Asked Answered
D

1

8

In C, local variables exist inside of a function and contain the values like this:

void main(){
    int a = 5;
    int b = 9;
}

In the Gforth manual, they describe the local variables like this:

: swap { a b -- b a }
  b a ;
1 2 swap .s 2drop

but it seems like a function which is taking two arguments, a and b.

Another tutorial on the Forth language shows a variable like this:

variable a
3 a !    ( ! to store the value )

So, which one is correct?

Deuterogamy answered 31/3, 2022 at 16:35 Comment(2)
Probably refresh your terminology. "Local variable" is well-defined in Forth; it's a variable which you declared in { ... } which goes out of scope at the end of the definition. Your other example is not a local variable.Hemotherapy
Right. variable declares a global variable. In standard Forth you can't even put a variable declaration inside a word definition, so there's not much room for confusion between the two.Miasma
I
10

In Forth, local variables are described by the following syntax (see also 13.6.2.2550 {:):

{: args [ | vals ] [ –– outs ] :}

where each of args, vals and outs represents space-delimited names (the parts in square brackets are optional). These names are interpreted as follows:

  • args names are for locals that are initialized from the data stack, with the top of the stack being assigned to the rightmost name in args;
  • vals names are for locals that are uninitialized;
  • outs names are ignored (they are for documentation purposes only, if any).

Gforth uses { ... } notation for locals as an alternative to the standard one.

So, swap can be defined as:

: swap {: a b :} b a ;

It takes two values from the stack into a and b local variables, and then puts them back on the stack in the reversed order.

An example of use an uninitialized local variable:

: exch ( x2 addr -- x1 ) {: a | x1 :}
  a @ to x1 a ! x1
;

The optional -- ... part is allowed to mimic a stack diagram, i.e., to unite the declaration of locals and the stack diagram for a word. For example:

: umin {: u2 u1 -- u2|u1 :} u2 u1 u< if u2 else u1 then ;

Without special optimizations, performance of local variables is slightly worse than of a little stack juggling.

Interstice answered 10/5, 2022 at 18:16 Comment(2)
Re "performance of local variables is slightly worse than of a little stack juggling": Can you quantify that? Do you have some measurements? What system was it tested on?Arachnoid
@PeterMortensen, have a look at a discussion in comp.lang.forth re local variables performance. There are some examples there.Interstice

© 2022 - 2024 — McMap. All rights reserved.