int a = 1, b = 2;
int c = a*b + b==0; // c = 0
cout << a*b + b==0; // outputs 4
c
evaluates to 0
because the operator precedence of the *
and +
operators is higher than ==
as a result of which c
essentially evaluates to (a*b+b)==0
which is false.
Why does putting the same expression in a cout
statement output 4?
Because the precedence of these operators are operator*
> operator+
> operator<<
> operator==
. Then cout << a*b + b==0;
is equivalent with (cout << ((a*b) + b)) == 0;
.
Then the result of ((a*b) + b))
, i.e. 4
will be printed out, then the returned value of (cout << ((a*b) + b))
, i.e. cout
is compared with 0
. Before C++11 cout
could be implicitly converted to void*
via operator void*, which returns a null pointer when steram has any errors. So here it's compared with 0
(i.e. the null pointer), and does nothing further more with the result.