The Delphi Bug List

Entry No.
629
Compiler - Hints and Warnings
The compiler does not issue a warning when a function returning a string never initializes Result.
1.02 2.01 3.0 3.01 3.02 4.0 4.01 4.02 4.03 5.0 5.01 6.0 6.01 6.02 Kylix 1.0
N/AExistsExistsExistsExistsExistsExistsExistsExistsExistsExistsExistsExistsExistsExists
Description
Reported by Jordan Russell
The compiler does not issue a warning when a function returning a string never initializes Result. This behavior may lead one to assume that Delphi clears string Result variables automatically as it does with local variables of type string, but that is not the case.

Consider the following code:

function Test(AssignResult: Boolean): string;
begin
  if AssignResult then
    Result := 'a';
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  S: string;
begin
  S := Test(True);
  S := Test(False);
  Caption := S;
end;

What will the value of S be at the time it's assigned to Caption? Interestingly, it will be 'a'. The first call to the Test function will set Result to 'a'. The second call to the Test function will not assign anything to Result. The reason why it returns 'a' anyway is Delphi internally passes the same string variable in both calls without clearing it in between.

I consider the lack of a warning a compiler bug because Delphi does issue a warning on similar-looking functions that return Integers instead; for example:

function Test(AssignResult: Boolean): Integer;
begin
  if AssignResult then
    Result := 1;
end;
Solution / workaround
Always initialize Result to '' if you want to return an empty string. Not assigning Result does not guarantee an empty string will be returned.

The above code sample should be changed to:

function Test(AssignResult: Boolean): string;
begin
  if AssignResult then
    Result := 'a'
  else
    Result := '';
end;
User-contributed comments
Khash Sajadi
03 Mar 2004  11:52 AM GMT
This problem also occures when the function result is a variant. (Tested under Delphi 5 SP1 Enterprise)
Khash Sajadi
03 Mar 2004  03:59 PM GMT
After spending some time on this issue I think I can be pretty sure that this happens for all non fixed-size result types like strings (any type), sets, records and arrays (dynamic and static). I think Borland should think about this issue as it becomes critical as the size of the project gets bigger.
Latest update of this entry: 2002-02-28

Post a comment on this bug


Index page
Delphi Bug List home page
The Delphi Bug Lists are presently maintained by Jordan Russell, who has taken over this task from Reinier Sterkenburg since August 2000.
All feedback is appreciated. See also the feedback section of the Delphi Bug List home page.