Delphi: function Result not emptied during for loop

对着背影说爱祢 提交于 2019-12-03 20:16:06

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5102843/delphi-function-result-not-emptied-during-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!