Blockly – Operator Precedence

  • Platform information:

    • Hardware: Pi4 8GB
    • openHAB version: 5.1.4
  • Issue of the topic: Blockly – Operator Precedence with the logical and/or with multiple operands

  • I expected that the following logical expression should be the same, but they are not:

    But switching to the generated code it shows, that its different:

  • I expectet for both cases that only if Zeitraum_Nacht is ON and one of Bewegung is on the expression is True. Means in both cases the or expression should be in brackets

  • Is the an explanation, why this is not the case?

Thanks for the help :slight_smile:

The frst one should become something like:

if cond1 && cond2 || cond3

Which would be: if con1 is true and cond2 is true return true or if cond3 is true return true. The conditions are evaluated && first and then ||.

The second one should become something like

if cond1 && (cond2 || cond 3)

So this one would be: if either cond2 is true or cond3 is true and cond1 is true return true.

Boolean operations follow a strict order of operations similar to PEMDAS in math. The order is:

  1. parens
  2. NOT
  3. AND
  4. OR

When there are more than one of the same operation, the expression is evaluated from left to right.

So the || operation inside the parens gets done first. Then the result of that is used in the && operation. Given the order of operations, putting the || inside parens is the only way to make sure that is done first before the &&.

Only the second one does that.

Another way to write the first one would be if (cond1 and cond2) || cond3 or if cond3 || cond2 && cond1 because the && operation is done before the || operations when there are no parens.

Edit: my last example was wrong, had to fix it.