Post Reply 
variable initial value - bug? (rev. 8151)
09-28-2015, 06:55 AM
Post: #9
RE: variable initial value - bug? (rev. 8151)
Hello,

It's a question of scope.

local k:=1; // or k=1, the syntax is flexible there

since your statement is at the PROGRAM level, the scope of the k variable is program scope. So, this variable is accessible for the WHOLE program, every function thereof.
The variable is NOT accessible from outside of the program (unless fully qualified: program_name.k)

k will stay in memory until the program is deleted or changed.

Note that the local here is optional (default). The other option for a Program scope variable is EXPORT.
EXPORT k:=1;
Creates a variable k which will act EXACTLY like local k:=1; with one exception. You can use it from outside the program without having to fully qualify it.
That variable WILL appear in the variable catalog and you can type k on the command line and get its value.


What you are looking for is a Function scope local variable:
function(a)
begin
local k:=1;
return k+a;
end;

Here, k scope, and life expectancy is limited to the call to function. the variable is created when the local statement is encountered (it does not exist before), and it dies with the code block in which it is embedded.

so:
function(a)
if a<1 then
begin
local k:= 1;
return a+k;
else
local k:= 2;
return a+k;
end;
end;

Will create 1 or the other k variables, with values 1 or 2 depending on the case.
but once the end of the if clause is reached, then k stops to exist as its program block ends.

You can also create, in a function, a new program block, with a new k variable, which will 'take over' the k name for as long as its alive, with all the potential for trouble that it can bring, as in:

local a;
for a:=0 to 100 do
if a>50 then
local b:= a+1;
local a:= b+a;
print (a); // at a=50, prints 103 (b= a+1=52; new a= 52+51=103
// (yes, at the time of evaluation of the b+a, the new a
//does not YET exists))
end;
end;

Cyrille

Although I work for the HP calculator group, the views and opinions I post here are my own. I do not speak for HP.
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: variable initial value - bug? (rev. 8151) - cyrille de brébisson - 09-28-2015 06:55 AM



User(s) browsing this thread: 1 Guest(s)