Delphi: function Result not emptied during for loo

2019-02-10 07:27发布

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

2条回答
神经病院院长
2楼-- · 2019-02-10 07:55

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.

查看更多
淡お忘
3楼-- · 2019-02-10 08:07

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.

查看更多
登录 后发表回答