c++operatorsoperator-precedence

How do C++ operators work, for "||", "!", and "&&"?


Given that x = 2, y = 1, and z = 0, what will the following statement display?

printf("answer = %d\n", (x || !y && z));

It was on a quiz and I got it wrong, but I don't remember my professor covering this. I know the answer I get is 1, but why?


Solution

  • The expression is interpreted as x || (!y &&z)(check out the precedence of the operators ||, ! and &&.

    || is a short-circuiting operator. If the left operand is true (in case of ||) the right side operand need not be evaluated.

    In your case x is true, so being a boolean expression the result would be 1.

    The order of evaluation of && and || is guaranteed to be from left to right.