'Does bc not limit a variable's scope?

Define the function in basic calculator bc as

define void f () { test=42; print "all done\n"; }

I'd have thought the value of test would be limited to the scope of the function f, but no, test equals 42 globally. Is there no way to limit the scope of variables in bc functions? I.e. is there are way to define local variables in bc?



Solution 1:[1]

You need to specify an AUTO_LIST in your function definition. From the bc manual,

`define' NAME `(' PARAMETERS `)' `{' NEWLINE
    AUTO_LIST   STATEMENT_LIST `}'

[...]


The AUTO_LIST is an optional list of variables that are for "local"
use.  The syntax of the auto list (if present) is "`auto' NAME, ... ;".
(The semicolon is optional.)  Each NAME is the name of an auto
variable.  Arrays may be specified by using the same notation as used
in parameters.  These variables have their values pushed onto a stack
at the start of the function.  The variables are then initialized to
zero and used throughout the execution of the function.  At function
exit, these variables are popped so that the original value (at the
time of the function call) of these variables are restored.  The
parameters are really auto variables that are initialized to a value
provided in the function call.  Auto variables are different than
traditional local variables because if function A calls function B, B
may access function A's auto variables by just using the same name,
unless function B has called them auto variables.  Due to the fact that
auto variables and parameters are pushed onto a stack, `bc' supports
recursive functions.

So to keep the test variable "local" in your function, you'd use

define void f () { auto test; test=42; print "all done\n"; }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1