8
votes

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.

1
Have you tried this?user202729
@ user202729 I did not turn off any warning. also I get return value might be undefined for other cases.Shahram Banazadeh
There are som static code analyzers that can help identify this type of errors, see Are there any static code analysis tools for Delphi/Pascal?LU RD
@LURD Tried this one. It has some good features and some bugs ( like including commented part of code in analyze,loop varaibale not used and short ciruceuted if statment wrong detects) But it does not recognize this faults too.ThanksShahram Banazadeh
@LURD Fixinsight found IT!Shahram Banazadeh

1 Answers

9
votes

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.