0

Due to a bug in my code I stumbled upon this scenario by accident: -

function Bogus: string;
begin
end;

var
  s: string;
begin
  s:='Original value';
  s:=Bogus;
  MessageDlg(s, mtInformation, [mbOK], 0);
end.

Will show a dialog of Original value where the non-result of my function call has no effect on my var; I would have expected it to be empty.

Is this the expected behaviour? Can it be relied upon? Would anyone actually implement this on purpose??!?

I've been using Delphi since 1995 and have never encountered this before.
(Even to this day I still won't select text from the cursor placed by the IDE on a compile error as that used to crash Delphi 1.0!!!)

Jon
  • 812
  • 2
  • 11
  • 18

1 Answers1

3

Behind the scenes, the string return value of Bogus() is passed using a hidden var parameter (not an out parameter, like you are thinking of), as if you had written your code like this instead:

procedure Bogus(var Result: string);
begin
end;

var
  s: string;
begin
  s:='Original value';
  Bogus(s);
  MessageDlg(s, mtInformation, [mbOK], 0);
end.

Since Bogus() does not assign anything to its Result, the original string value is preserved (undefined behavior), which is why you are able to see it in the MessageDlg() afterwards.

However, this is a widely known implementation detail that you should NOT rely on. You should always assign something to the Result of a function. The documentation merely says:

If the function exits without assigning a value to Result or the function name, then the function's return value is undefined.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Aha, thanks so much for that. I did search for an answer first but didn't think of the correct words to search for obviously! The only concern I had was that it didn't yield a compiler hint / warning (at least in Delphi 6.0 - I didn't try all my compilers!). Thanks for your quick and clear answer :) – Jon May 14 '20 at 23:31