8

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.

MartynA
  • 30,454
  • 4
  • 32
  • 73
Shahram Banazadeh
  • 500
  • 1
  • 5
  • 15

1 Answers1

9

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • I use delphi berlin 10.1.( I edited my post to add this detail )Then I think I must read my changed codes again . and do not code when I am so sleepy, Never! ;) Thank you for answer . – Shahram Banazadeh Feb 04 '18 at 08:36
  • 1
    @David: Nope, not even Tokyo 10.2.2 warns about this, if the result type is managed. Tried with dynarrays and strings: no warning. Integers or Doubles: warning. So nothing has changed. – Rudy Velthuis Feb 04 '18 at 22:47
  • 1
    FWIW: https://quality.embarcadero.com/browse/RSP-16880 - as for the behavior itself I think Allen Bauer once mentioned that the warnings are being generated at a stage after the parameter list is being generated and thus does not know that this var parameter is actually the function result making this rather complicated to fix. – Stefan Glienke Feb 05 '18 at 09:25
  • 1
    @Stefan: I assume the unassigned result check is done at that later stage, not just the generation of the warnings. But ISTM that if they really cared, they could carry along a flag that indicates that a certain parameter is supposed to be the result and check that too. – Rudy Velthuis Feb 05 '18 at 11:49