Alex Rivera | Logout

In C++, why does true && true || false && false == true?

Asked 2010-10-31T05:06:32.310
18

I'd like to know if someone knows the way a compiler would interpret the following code:

#include <iostream>
using namespace std;

int main() {
 cout << (true && true || false && false) << endl; // true
}

Is this true because && has a higher precedence than || or because || is a short-circuit operator (in other words, does a short circuit operator disregard all subsequent expressions, or just the next expression)?

Edit
Report

2 Answers

1

about the true && true || infiniteLoop() && infiniteLoop() example, neither of the infinite loop calls are being evaluated because of the two characteristics combined: && has precedence over ||, and || short-circuits when the left side is true.

if && and || had the same precedence, the evaluation would have to go like this:

((( true && true ) || infiniteLoop ) && infiniteLoop )
(( true || infiniteLoop ) && infiniteLoop )
=> first call to infiniteLoop is short-circuited
(true && infiniteLoop) => second call to infiniteLoop would have to be evaluated

but because of &&'s precedence, the evaluation actually goes

(( true && true ) || ( infiniteLoop && infiniteLoop ))
( true || ( infiniteLoop && infiniteLoop ))
=> the entire ( infiniteLoop && infiniteLoop ) expression is short circuited
( true )
answered 2010-10-31T17:54:51.950
0

This is a sequential illustration:

  (true && true || false && false)
= ((true && true) || (false && false))  // because && is higher precedence than ||, 
                                        //   like 1 + 2 * 3 = 7  (* higher than +)
= ((true) || (false))
= true

but also note that if it is

(true || ( ... ))

then the right hand side is not evaluated, so any function there is not called, and the expression will just return true.

answered 2010-11-01T03:00:49.583

Your Answer