Insight 7.8.1.
When in doubt, use parentheses. They make your code easier to read and understand. Code that depends on every reader and editor correctly remembering every detail of the order of operations can easily hide bugs.
!
or ++
bool beforeChristmas = month < 12 || (month == 12 && day < 25);
is evaluated. Assume month = 12
and day=26
:
bool beforeChristmas = month < 12 || (month == 12 && day < 25);
bool beforeChristmas = month < 12 || (true && false);
bool beforeChristmas = month < 12 || (false);
bool beforeChristmas = true || (false);
bool beforeChristmas = true;
!x == 10
does not calculate “x does not equal 10”. The !
is evaluated first and only is applied to x
. So we get !x
. If x is a number, this just turns any value but 0 to 0 and turns 0 to 1. Then we compare that value to 10! To write that correctly we need to write !(x == 10)
or x != 10
.
*
comes before +
. But it is also true that &&
always comes before ||
. That means that we could write the expression above as month < 12 || month == 12 && day < 25
. The comparisons would happen first, then the &&
, then the ||
. But the expression is much easier to read when the parentheses are there.