+ 4
How to understand this code ↓↓↓ and these relationship operators ↓↓↓ ??
#include<stdio.h> #include<stdlib.h> int main(){ int x = 10, y = 20 , z = 5 , i ; i = x < y < z ; printf("%d\n ", i); // Output : 1 // i can't catch why 1 return 0; }
8 Antworten
+ 9
It is because of how you are chaining
x < y < z together, which will non-intuitively result in true instead of false, due to how it is evaluated.
If you break it up into smaller fragments you'll probably understand better.
Process it from left to right (this is undefined depending on the compiler used).
x < y results in true because x is less than y.
However, when you now do the next comparison, you'll have;
true < z
Since true and z are of different types, boolean and int, the boolean is implicitly converted to an int resulting in;
1 < z
This evaluates to true, so i is equal to the boolean true.
Now during the fprint() i is output as an int so it is converted to the value of 1 and that is why 1 is what is output instead of 0.
+ 4
Mik_RDC
1 < z will result in the bool value true, but since i is of type int this bool value is implicitly converted to the int value 1, so i is equal to 1 not true. Sorry, for the confusion.
+ 3
ChaoticDawg i can catch now big thanks to your help
+ 3
Kyrill I was think that befor :
10 < 20 = 1 and 20 < 5 = 0
1 and 0 = 1&&0 or 1*0 = 0
+ 2
BeCause
10 < 20 = 1 and 20 < 5 = 0
1 and 0 = 1&&0 or 1*0 = 0
+ 2
ChaoticDawg big thanks but when it take 1 < z it became a bool vs a int that can't work or how . if you put it or assign it into a variable this variable must be of wich type int or other
+ 2
There are no booleans in C. Just 1 and 0.
so :
int x = 10, y =20, z = 5, i;
i = x < y < z;
1) x < y ( 10 < 20 ) // it's 1 (true)
2) 1 < z ( 1 < 5 ) // it's again 1 (true)
3) i = 1 // and the next step we print this result
+ 1
So: < returns a true/false value. True is considered 1 and false is considered 0 (in binary). If you 'deconstruct' it, it'll look like this:
x < y < z ->
10 < 20 < 5 ->
10 < 20 = (true)1 ->
1 < 5 = (true)1
Basically, we're going left-to-right. 10 is less than 20, so we get true, or 1. True (or 1) is less than 5, so we get true again (or 1).
This is simply odd handling of C. It converts the bool to an int because the variable is a type of 'int'. Try this in Python, Lua, JS or any language that is more high-level (and has dynamic types) and you will get 'true' rather than '1'.
Therefore, our output shall be 1, or true.