Delphi: function Result not emptied during for loop
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 chec开发者_如何学Ck = 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.
精彩评论