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

1

7

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.

Dorelle answered 24/5, 2013 at 8:13 Comment(0)
P
18

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.

Parasiticide answered 24/5, 2013 at 8:18 Comment(6)
+1 and lol for the name of your suppress... method. Great way of suppressing those hints. Much better than adding a comment to some arbitrary statement that serves the same purpose.Mcentire
@MarjanVenema Yes, I tend to favour code that obviates the need for comments.Parasiticide
Nice trick! I had tried wrapping the Assert in an inline function (that got optimized away as well), but the hint was still there, with yours it's gone!Dorelle
@EricGrange Thanks. What would be really nice would be if we could have some fine grained control with compiler directives. Like {$SUPPRESSHINTS v} or some such.Parasiticide
@DavidHeffernan: So do I, but method calls can be a burden in highly performant code. Inlining a method that doesn't do anything, would thus always be inlined and be optimised away, just hadn't occurred to me (or any of us at work).Mcentire
@MarjanVenema I only had the idea an hour ago right after I cleared the bleeding away!Parasiticide

© 2022 - 2024 — McMap. All rights reserved.