Some mistakes existing in the program and I dont know why

I know there must be some problems with the boolean expression in each if-statement. A friend tells me that it is wrong to write like this. However, it gives the values of b and c (i.e. 20, 0) when I run it.

Why and how?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  #include <iostream>
using namespace std;

int main()
{
    int a = 10;
    int b = 20;
    int c = 0;

    if (a < b < c)
    {
        cout << a << endl;
    }

    if (b < c < a)
    {
        cout << b << endl;
    }

    if (c < b < a)
    {
        cout << c << endl;
    }
    return 0;
}
You can't write the statement all together as one (a < b < c). You have to write it separately (a < b && b < c).
Less-than is a binary operator. Binary operator has two operands and returns one value. Less-than is a relational operator. The return value of a relational operator is bool.

Operators in same grouping have order of evaluation. Concatenated relational operators evaluate from left to right. Therefore, a < b < c means same as (a < b) < c.

Lets evaluate the leftmost part. Substitute values first:
(10 < 12) < c
and evaluate:
true < c
Now we can substitute the rest:
true < 0
What does that evaluate to?


Different operators have different precedence. Less-than has higher precedence than logical and. Therefore,
a < b && b < c
is same as
(a < b) && (b < c)


PS. Your original program does not handle all orderings of a, b, c; just three cases.
Topic archived. No new replies allowed.