Hi Hardcore.
I chanced across this today and I don't think the code presented is doing what you intended.
You're looking to set limitingAmount once and call it many times later on. Correct?
In that case you wouldn't use an integer pointer you would use a function pointer. If you set an integer pointer once and reference it over and over, you will get the same answer. Unless someone else changes the integer it is pointing to. If the other functions were going to change an integer, you might as well use a global integer and avoid the pointers completely.
In the other example, you were setting the integer pointer to the
results of a function. The question is, what is the address of the results of a function? I would expect them to be somewhat random and unsafe to use. I changed the sample to show what happens when you do this:
program new;
var
LimitingAmount: ^Integer;
featherCount: integer = 3;
shaftCount:integer = 12;
i: integer;
function feathersLeft: Integer;
begin
writeln('executing...');
Result := featherCount;
inc(feathercount);
end;
function shaftsLeft: Integer;
begin
writeln('executing2...');
Result := shaftCount;
dec(shaftCount);
end;
var s:integer;
begin
if shaftsLeft() > feathersLeft() then
LimitingAmount :=@feathersLeft()
else
LimitingAmount :=@shaftsLeft();
for i := 1 to 10 do
writeLn(LimitingAmount^);
end.
Results:
Compiled successfully in 234 ms.
executing2...
executing...
executing...
4
4
4
4
4
4
4
4
4
4
Successfully executed.
So it called feathersLeft once in the if and that changed featherCount to 4. Then we assigned the integer pointer to results of featherCount (which was still 4). The other times we printed it, we got the same result. If other functions called feathersLeft() a few times and we peeked at limitingAmount^ we would see the updated results (I tried it). That's kind of a quirk of lape I would say and I don't know how consistent it would be. But it is not calling featherCount when we reference limitingAmount to get a fresh count.
If we do the same with a function pointer you see it runs the function 10 times. When you use a function pointer shaftsLeft or feathersLeft get called indirectly by referencing limitingAmount():
program new;
var
LimitingAmount: function():integer;
featherCount: integer = 3;
shaftCount:integer = 12;
i: integer;
function feathersLeft: Integer;
begin
writeln('executing...');
Result := featherCount;
inc(feathercount);
end;
function shaftsLeft: Integer;
begin
writeln('executing2...');
Result := shaftCount;
dec(shaftCount);
end;
var s:integer;
begin
if shaftsLeft() > feathersLeft() then
LimitingAmount :=@feathersLeft
else
LimitingAmount :=@shaftsLeft;
for i := 1 to 10 do
writeLn(LimitingAmount());
end.
Results:
Compiled successfully in 234 ms.
executing2...
executing...
executing...
4
executing...
5
executing...
6
executing...
7
executing...
8
executing...
9
executing...
10
executing...
11
executing...
12
executing...
13
Successfully executed.
Let me know if that doesn't make sense.