'Why is if (2 < 9 < 3) true?
This was a question in my preparation exam:
int val = 0;
int x = 0;
int y = 1;
if (x < val < y)
printf(" true ");
else
printf(" false ");
Why is this true? I tried changing x and val and it ignored those changes, as long as y was larger than 0 (so 1, 2, 3...) the statement was true. So for example: if (3 < 9 < 2) will be true.
Solution 1:[1]
( 2 < 9 < 3 ) is evaluated as ( ( 2 < 9 ) < 3).
In the first step 2 < 9 is evaluated to be true, which is represented as integer value 1 and results in ((1) < 3) for the second step.
That is obviously true.
You probably wanted something like ((x < val) && ( val < y)).
Solution 2:[2]
The first is check whether x < value. If true, it return 1 so the next is check whether 1 < y.
Solution 3:[3]
First you check x and val. If its value is correct, you convert it to 1 and check it with y.
Solution 4:[4]
If you build with -Wall option using GCC compiler you will get a warning like this:
<source>:7:11: warning: comparisons like 'X<=Y<=Z' do not have their mathematical meaning [-Wparentheses]
if (x < val < y)
Detailed explanation of this warning can be found in GCC documentation. The relevant part is as following:
-Wparentheses
...
Also warn if a comparison like x<=y<=z appears; this is equivalent to (x<=y ? 1 : 0) <= z, which is a different interpretation from that of ordinary mathematical notation.
...
Solution 5:[5]
NOTE: Comparisons in C follow the left to the right approach. (if all operators are of same priority)
Thus, evaluation of (2 < 9 < 3) will be done in 2 steps:
- step 1. evaluation of
(2 < 9): it is true, thus, integer value=1. - step 2. evaluation of
( (2 < 9) < 3 )i.e(1 < 3): it is also true.
Solution 6:[6]
I think you wanted (2 < 9) && (9 < 3).
In C, usually operators follow left to the right approch(except operators like =, -=, +=, etc.). Operator <, > follows left to the right approch too. So, 2<9<3 in C means (2 < 9) < 3. 2 < 9 is 1, so, the value of 2 < 9 < 3 is 1.
You can fix it with (2 < 9) && (9 < 3).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Itati |
| Solution 3 | Kadir Y?ld?r?m |
| Solution 4 | ks1322 |
| Solution 5 | Ayush |
| Solution 6 | cout Hello world endl |
