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