Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi compiler does not warn about this code

Debugging my code, I noticed that the Delphi compiler (Berlin 10.1) does not warn about functions which are without a return value. Is this normal?

A simple example:

function f(s:string):String;
begin
  stringreplace(s,#32,'',[rfReplaceAll]);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
   showmessage(F('te st'));
end;

this line

 stringreplace(s,#32,'',[rfReplaceAll]);

Should be

result:= stringreplace(s,#32,'',[rfReplaceAll]);

No warning!

I think it should warn "return value might be undefined". But it does not. I changed and rewrote some part of old codes in last days. I am afraid I have this kind of mistake in my application.

like image 959
Shahram Banazadeh Avatar asked Feb 04 '18 08:02

Shahram Banazadeh


1 Answers

It's a compiler defect. Managed type return values are implemented as var parameters. So once the compiler has transformed the function to be a procedure with an extra var parameter for the return value, it sees a var parameter that it presumes was initialized by the caller. That is the root cause of the issue. I'm not excusing it though, it's a clear defect, and a bad one. I'm just giving a bit of background as to how this can happen.

There's not a lot that you can do about this. Perhaps the very best thing you can do is make sure that your code has strong unit test coverage. Static analysis tools like FixInsight can also be deployed to help root out such mistakes in your code.

like image 70
David Heffernan Avatar answered Oct 27 '22 08:10

David Heffernan