Reputation: 17
am just learning C++ programming and my problem is that am trying to compare more than one variables and is not working. This is what I typed : if ( a > b > c)
.
Upvotes: 1
Views: 119
Reputation: 56557
It doesn't work like this, as the first expression a > b
evaluates to a boolean, which is converted (because of the comparison with c
) to either 0
or 1
, depending on its truth value. You then attempt to compare it with c
, which is not what you want. Use
if ( (a > b) && (b > c) )
instead. This way you compute the logical AND
of two booleans, and if both are true
, then the mathematical statement a > b > c
is true (by transitivity).
If you compile with all warnings on, the compiler will (probably) warn you. At least g++ is saying:
warning: comparisons like 'X<=Y<=Z' do not have their mathematical meaning [-Wparentheses]
Upvotes: 4
Reputation: 4703
You have to seperate both conditions via AND(&&) Operator
if ( (a>b) && (b > c) ){
//code
}
Upvotes: 3