12

I want to disable a specific warning (W1035) in my code, since I think that the compiler is wrong about this warning:

function TfrmNagScreen.Run: TOption;
begin
  if ShowModal = mrOk then
    Result := TOption(rdgAction.EditValue)
  else
    Abort
end;

There is no way the result could be undefined, since Abort throws EAbort.

I tried:

  • {$WARN 1035 Off}: Apparently this only works for some specific errors (see Documentation)
  • {$W-1035}: Does nothing at all

I know I can switch off the warning globally in the project options, or using {$WARNINGS OFF}, but that is not what is intended here.

Edit: I have QC'ed this now as #89744.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113
  • While its true the compiler sometimes gets confused and reports this warning without cause, in this case the compiler is technically correct. Result is not assigned before the conditional and is only assigned on the true branch of the conditional. The fact that the function returns prematurely if the condition is false is irrelevant to the compiler. – Kenneth Cochran Nov 17 '10 at 18:28
  • @codeelgance: Quite true, but I think `Abort` is a builtin function and the compiler could recognize the situation. – Jens Mühlenhoff Nov 17 '10 at 21:21

3 Answers3

13

you can't disable this warning globally, but you can use the {$WARN NO_RETVAL OFF} to disable locally the warning.

{$WARN NO_RETVAL OFF}
function TfrmNagScreen.Run: TOption;
begin
  if ShowModal = mrOk then
    Result := TOption(rdgAction.EditValue)
  else
    Abort
end;
{$WARN NO_RETVAL ON}
RRUZ
  • 134,889
  • 20
  • 356
  • 483
9

I don't have a Delphi compiler available at the moment, but rearranging the code to remove the if..else might make the warning go away:

function TfrmNagScreen.Run: TOption;
begin
  if ShowModal <> mrOk then
    Abort;

  Result := TOption(rdgAction.EditValue);
end;

See also How to disable a warning in Delphi about “return value … might be undefined”?.

Community
  • 1
  • 1
WileCau
  • 2,057
  • 1
  • 24
  • 34
1

You can use a neat trick to fool the compiler. Define a library function as so:

procedure Abort(var X);
begin
  SysUtils.Abort;
end;

You can then write your function as:

if ShowModal = mrOk then
  Result := TOption(rdgAction.EditValue)
else
  Abort(Result)

The compiler thinks you've written to Result since it's a var parameter and it stops bleating.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490