bc 不限制变量的范围吗?

Does bc not limit a variable's scope?

basic calculator bc中的函数定义为

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

我原以为 test 的值会限制在函数 f 的范围内,但不, test 在全局范围内等于 42。有没有办法限制bc函数中的变量范围? IE。有没有办法在 bc 中定义局部变量?

您需要在函数定义中指定 AUTO_LIST。来自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.

因此,要在您的函数中保持 test 变量为“本地”,您需要使用

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