Why does this program not output a boolean value?

Viewed 257
#include <iostream>
using namespace std;
int main()
{
    int a = 8;
    cout << "ANDing integer 'a' with 'true' :" << a && true;
    return 0;
}

Why does this program output 8 and not 1 (for true)?

4 Answers

If you look at operator precedence, you will find that the left-shift operator << has a higher precedence than the logical AND operator &&.

As such, it is evaluated as:

(cout << "ANDing integer 'a' with 'true' :" << a)  &&  true;

which prints 8.

In the expression 8 && true 8 is evaluated first (and in this turn also streamed). Than true is evaluated and the operator returns true after that. But than the 8 is already in the stream. If you put (8 && true) instead, the parentheses are evaluated first and the result is guarantreed to be 1, which then is streamed.

This behavior is called Operator Precedence - which describes the order in which the operators are executed (in your case && and <<).

The logical AND operator, &&, works with expressions.
The first expression is evaluated. If the first expression is false, no more evaluations. Otherwise the second expression is evaluated.
Next, the result of the two Boolean expressions is returned.

So, the first expression is evaluated:

cout << "ANDing integer 'a' with 'true' :" << a

A side effect of the evaluation is the following output to the console:

ANDing integer 'a' with 'true' :8

Your output is generated because it is a side-effect of evaluating the first expression.

The logical AND operator && works with expressions. If both are true returns true and false if otherwise.

cout << "ANDing integer 'a' with 'true' :" << a && true;

is being evaluated as:

(cout << "ANDing integer 'a' with 'true' :" << a)  &&  true;

due to operator precedence (<< having higher precedence than AND &&) giving you the print of: 8 if we do the following change: (a && true); it will give you the print of: 1

Related