Why is order of expressions in if statement important

c, c++, if-statement, java

Solution

Its not just about choosing the most likely condition on the left. You can also have a safe guard on the left meaning you can only have one order. Consider

if (s == null || s.length() == 0) // if the String is null or empty.

You can't swap the order here as the first condition protects the second from throwing an NPE.

Similarly you can have

if (s != null && s.length() > 0) // if the String is not empty

The reason for choosing the most likely to be true for `||` or false for `&&` is a micro-optimisation, to avoid the cost of evaluated in the second expression. Whether this translates to a measurable performance difference is debatable.

Problem

Suppose I have an `IF` condition : ``` if (A || B) ∧ | | left { // do something } ``` Now suppose that `A` is more likely to receive a true value then `B` , why do I care which one is on the left ? If I put both of them in the `IF` brackets , then I know (as the programmer of the code) that both parties are needed . The thing is , that my professor wrote on his lecture notes that I should put the "more likely variable to receive a true" on the left . Can someone please explain the benefit ? okay , I put it on the left ... what am I gaining ? run time ?

Original source