user466534
user466534

Reputation:

boolean type manipulation

this code

#include <iostream>

using namespace std;
int main(){
  bool t=false;
  cout<<t &&(!t)<<endl;

  return 0;
}

shows me error like this

invalid operands of types 'bool' and '' to binary 'operator<<'

What is wrong? I can't understand this, please explain it to me. I think that && and ! is defined in c++.

So what is wrong?

Upvotes: 4

Views: 454

Answers (5)

N_A
N_A

Reputation: 19897

"invalid operands of types 'bool' and '' to binary 'operator<<'"

This means that the second << operator is trying to execute on (!t) and 'endl'.

<< has a higher precedence than && so your cout statement executes like this:

(cout << t ) && ( (!t) << endl );

Add parenthesis to fix this:

cout << (t && (!t) ) << endl ;

Look here for order of operations when statements are not evaluating as expected.

Upvotes: 16

iammilind
iammilind

Reputation: 70088

The problem is with operator precedence, as && has lower precedence than <<.

cout<<(t && (!t))<<endl;  // ok!

Also for any bool variable t the expression t && (!t) always results in false and t || (!t) always results in true. :)

Upvotes: 2

visitor
visitor

Reputation: 1801

&& has lower precedence than <<, so the statement is evaluated as (cout << t) && (!t << endl);

C++ operator precedence

Upvotes: 3

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81724

You need some more parentheses:

cout << (t && !t) << endl;

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477514

Add parentheses to get the precedence of operators right:

cout << (t && !t) << endl;

Equivalently:

cout << false << endl;

Upvotes: 6

Related Questions