Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird boolean conversion (?)

Tags:

c++

Explain pleasy why second expression returns false

   cout << (4==4) << endl; //1
   cout << (4==4==4) << endl; // 0
like image 872
Orange Fox Avatar asked Feb 06 '26 01:02

Orange Fox


1 Answers

(4==4==4) is basically ((4==4)==4) which is (true == 4) which is (1==4) 1 which is false 2 which is getting printed as 0.

Note that == has associativity left-to-right, but that doesn't matter (in this case) because even if it had associativity right-to-left, the result would have been the same.


1. Due to integral promotion.
2. Note that one might tempted to think 4 in (true==4) could be treated as true (after all 4 is non-zero, hence true). This thinking might conclude (true==4) is (true==true) which is true. But that is not how it works. It is the bool which gets promoted to int, instead of int to bool.

like image 92
Nawaz Avatar answered Feb 09 '26 00:02

Nawaz