开发者

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 && an开发者_StackOverflow中文版d ! is defined in c++.

So what is wrong?


"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.


Add parentheses to get the precedence of operators right:

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

Equivalently:

cout << false << endl;


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

C++ operator precedence


You need some more parentheses:

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


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. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜