Boolean Precedence
The above examples use parentheses to spell out the order of operations. The boolean not ! has a high precedence -- in (!a && b) the ! is evaluated on the a, before the &&. We could add in parenthesis (!(a && b)) to force the && to evaluate before the !. The && operator is higher precedence than ||, so in (a || b && c), the && happens first. There are parallels between the boolean operators and arithmetic: ! is like unary -, && is like *, || is like +. The comparison operators (<, <=, ==, ...) all have higher precedence than && and ||, so without parentheses, comparisons always happen before the && and ||. This is very convenient, since we can use <= to get some booleans, and then && and || to combine the booleans. So our earlier example:if (! ((style>=8) && (bribe>=5))) {works fine without parentheses around the comparisons, since the comparisons have high precedence than && ||:
if (! (style>=8 && bribe>=5)) {The not ! has a high precedence (as do all the unary operators), so we need parentheses to force the ! to evaluate after the >= and &&. Remember that all the unary operators, such as !, have a high precedence. To evaluate something before the !, we frequently need to put the something in parentheses like this: !(something). For example:
if (! i < 10 ) { ... // NO does not workThe precedence of the ! is too high, it wants to execute before the <. To fix this, we add parentheses around the (i < 10) so it goes first:
if (!(i < 10 )) { ... // Ok