is this normal?
for a := 1 to 10 do
x.test;
x.test;
x.test;
x.test;
function test: string;
begin
{$IFDEF DEBUG} DebugMessage('result check = '+Result,3); {$ENDIF}
result := result + 'a';
end;
10:39:59: result check =
10:39:59: result check = a
10:39:59: result check = aa
10:39:59: result check = aaa
10:39:59: result check = aaaa
10:39:59: result check = aaaaa
10:39:59: result check = aaaaaa
10:39:59: result check = aaaaaaa
10:39:59: result check = aaaaaaaa
10:39:59: result check = aaaaaaaaa
10:39:59: result check =
10:39:59: result check =
10:39:59: result check =
function result stack is not freed during a for loop? :O
Result
is treated as an implicit var
parameter to your function.
Imagine if you wrote it out explicitly this way:
procedure test(var result: string);
begin
result := result + 'a';
end;
for i := 1 to 10 do
test(s);
Then you would expect it to append to s
.
The fact that you are throwing away Result
each time you call it is why the compiler sometimes decides to finalise it. As @gabr points out, it elects not to finalize this implicit variable when inside a loop as an optimisation.
If you were to assign the result of test
to a string every time you called test
then you'd see the string get longer each time, it would never be re-initialized.
This is why you should always initialize your result variable. It looks like a local variable, but it is best thought of as a var
parameter.
Well, you should always initialize function result. Don't assume it will be set to proper value just because it is of a dynamic (in this case string) type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With