Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect in runtime if some Compiler Option (like Assertions) was set to ON?

What is the conditional to check if assertions are active in Delphi?

I would like to be able to do something to suppress hints about unused variables when assertions are not active in code like

procedure Whatever;
var
   v : Integer;
begin
   v := DoSomething;
   Assert(v >= 0);
end;

In the above code, when assertions are not active, there is a hint about variable v being assigned a value that is never used.

The code is in a library which is going to be used in various environments, so I'd be able to test for assertions specifically, and not a custom conditional like DEBUG.

like image 442
Eric Grange Avatar asked May 24 '13 08:05

Eric Grange


1 Answers

You can do this using the $IFOPT directive:

{$IFOPT C+}
  // this block conditionally compiled if and only if assertions are active
{$ENDIF}

So you could re-write your code like this:

procedure Whatever;
{$IFOPT C+}
var
   v : Integer;
{$ENDIF}
begin
   {$IFOPT C+}v := {$ENDIF}DoSomething;
   {$IFOPT C+}Assert(v >= 0);{$ENDIF}
end;

This will suppress the compiler hint, but it also makes your eyes bleed.

I would probably suppress it like this:

procedure SuppressH2077ValueAssignedToVariableNeverUsed(const X); inline;
begin
end;

procedure Whatever;
var
   v : Integer;
begin
   v := DoSomething;
   Assert(v >= 0);
   SuppressH2077ValueAssignedToVariableNeverUsed(v);
end;

The untyped parameter that the suppress function receives is sufficient to suppress H2077. And the use of inline means that the compiler emits no code since there is no function call.

like image 91
David Heffernan Avatar answered Nov 17 '22 03:11

David Heffernan