Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exam ques. on how booleans are handled in cout

Tags:

c++

I'm studying for upcoming exams and came across this past exam question which doesn't make sense to me.

Consider the following main function:

int main()
{
    int x = 0;
    cout << "x = " << x << ", (0 < x < 10) = " << (0 < x < 10) << endl;
    int x = 5;
    cout << "x = " << x << ", (0 < x < 10) = " << (0 < x < 10) << endl;
    int x = 10;
    cout << "x = " << x << ", (0 < x < 10) = " << (0 < x < 10) << endl;

    return 0;
}

When executed the program prints the following:

x = 0, (0 < x < 10) = 1
x = 5, (0 < x < 10) = 1
x = 10, (0 < x < 10) = 1

Explain exactly what has happened.


That's the question. As far as I know, the last line of output should be "x = 10, (0 < x < 10) = 0". What am I missing?

like image 687
Jack Finan Avatar asked Dec 10 '22 23:12

Jack Finan


2 Answers

What do you expect 0 < x < 10 to mean?

It doesn't check whether x is between 0 and 10, if that's what you thought.

< is a binary operator, which follows operator evaluation rules (precedence and associativity).

So 0 < x < 10 actually means (0 < x) < 10. You'll need two checks to get the result you want (left to you).

like image 79
Luchian Grigore Avatar answered Dec 30 '22 00:12

Luchian Grigore


0 < x < 10 does not do what you think it does. It does ( 0 < x ) < 10 which is not what you want. The result of 0 < x ( which will be true or false ) is then checked with < 10 which will also give result as true ( numerically equal to 1 ) or false ( numerically equal to 0 ).

You need

( 0 < x ) && ( x < 10 )

to check whether x in between them.

So, your first cout with x=0 is same as ( 0 < 0 ) which gives false and then 0 < 10 ( false is numerically 0 ), and hence the result is 1.

Similarly, your second cout at x=5 first gives result false and then with 0 < 10 , it gives true.

And finally, your last cout at x=10 first results true, and again true, so result is 1.

like image 40
Arun A S Avatar answered Dec 29 '22 23:12

Arun A S