Why it is treated as: a || (b && c || d); ? |
|
|
a || b && c || d
b && c
must be evaluated before the rest.b
has to be evaluated before b && c
b
b
is false THEN b && c
is falsec
b && c
, lets call it x
a
a
is true THEN a || x
is truea || x
is value of x
a || b && c
"y
"y
is true THEN return trued
AND return value of d
The && has higher precedence than ||. Therefore, b && c must be evaluated before the rest. |
|| || d a && b c |
|
|
abcd 0000: a b d 0 0001: a b d 1 0010: a b d 0 0011: a b d 1 0100: a b c d 0 0101: a b c d 1 0110: a b c 1 0111: a b c 1 1000: a 1 1001: a 1 1010: a 1 1011: a 1 1100: a 1 1101: a 1 1110: a 1 1111: a 1 |
++a + ++b * ++c + ++d
(++a) + (++b) * (++c) + (++d)
(++a) + ( (++b) * (++c) ) + (++d)
( (++a) + ( (++b) * (++c) ) ) + (++d)
( (++a) + ( (++b) * (++c) ) ) + (++d)
++b
and ++d
may be evaluated in any order:++b
before ++d
++d
before ++b
++b
and ++d
may overlap.a + b * c
means a + (b*c)
instead of (a+b) * c
a - b - c
is interpreted as (a-b) - c)
instead of a - (b-c)
.||
evaluates left to right, so f() || g()
will call f() first and then (if necessary because of short circuit evaluation) call g(). For most operators, the order of evaluation is undefined.you should avoid complicated expressions anyway, and there is a simple rule that can keep you out of trouble: if you change the value of a variable in an expression, don’t read or write it twice in that same expression. |
a + b * c
, it would be evaluated as a + (b* c) *
has a higher precedence than +
)a
first and c later or vice versa is of interest to people who write compilers (optimizers). The precise order of runtime evaluation of the above expression is not of much concern for us; in general, we play safe by following Stroustrup's simple rule. f() + g() * h()
, it would be evaluated as f() + (g())*h()) *
has a higher precedence than +
)f()
first and h() later or vice versa is of interest to people who write compilers (optimizers). The precise order of runtime evaluation of the above expression is not of much concern for us.
We need to know that if we write a + b * c, it would be evaluated as (a+b) * c (that * has a higher precedence than +) |
Whether the run-time evaluation is f() first and h() later or vice versa is of interest to people who write compilers (optimizers). The precise order of runtime evaluation of the above expression is not of much concern for us. |
f() + g() * h()
, the compiler can generate code to call all three functions in any order. It can be different from one compiler to the next, or even from one expression to the next in the same program with the same compiler. All you know for sure is that the result of g() and h() will be multiplied together and then added to the result of f(). If calling either of these functions can change the result of calling another then the behavior is undefined.