Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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

like image 724
hikari Avatar asked Feb 24 '11 09:02

hikari


Video Answer


2 Answers

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.

like image 133
David Heffernan Avatar answered Oct 14 '22 11:10

David Heffernan


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.

like image 37
gabr Avatar answered Oct 14 '22 10:10

gabr