Search code examples
delphidelphi-10.4-sydney

About comparison operators on Delphi


In Javascript, if i do the following command :

if (cond1 && cond2) {
}

The parser will stop if cond1 is false, no need to check cond2. This is good for performance.

In the same manner :

if (cond1 || cond2) {
}

If cond1 is true, there is no need to check cond2.

Is there something similar on newer Delphi versions ? I'm on the 10.4

Thanx


Solution

  • Yes, the Delphi compiler supports boolean short-circuit evaluation. It can be enabled or disabled using a compiler directive, but it is enabled by default, and often Delphi code assumes it to be enabled.

    This is very often used not only to increase performance, but to write code more succinctly.

    For instance, I often write things like

    if Assigned(X) and X.Enabled then
      X.DoSomething;
    

    or

    if (delta > 0) and ((b - a)/delta > 1000) then
      raise Exception.Create('Too many steps.');
    

    or

    if TryStrToInt(s, i) and InRange(i, Low(arr), High(arr)) and (arr[i] = 123) then
      DoSomething
    

    or

    i := 1;
    while (i <= s.Length) and IsWhitespace(s[i]) do
    begin
      // ...
      Inc(i);
    end;
    

    or

    ValidInput := TryStrToInt(s, i) and (i > 18) and (100 / i > 2)
    

    In all these examples, I rely on the evaluation to stop "prematurely". Otherwise, I'd run into access violations, division by zero errors, random behaviour, etc.

    In fact, every day I write code that assumes that boolean short-circuit evaluation is on!

    It's idiomatic Delphi.