i have been playing around with what would be considered valid C syntax and what wouldnt,
i tried 1<2<1
and to my surprise it is a valid C syntax, does anyone know what that would do or represent ?
i tried figuring it out by testing the value this kind of expressions take and changing the integer values but found no pattern.
CodePudding user response:
In C, when using a relational operator such as <
, the result will always be 1
if the condition is true, or 0
if the condition is false.
Due to the rules on operator precedence and associativity, the expression
1<2<1
is equivalent to:
(1<2)<1
The sub-expression (1<2)
is true, so it will evaluate to 1
, so the entire expression is equivalent to:
1<1
Since this expression is false, it will evaluate to 0
.
Therefore, writing 1<2<1
is equivalent to writing 0
.
CodePudding user response:
Because of the associativity of the <
operator, the expression 1 < 2 < 1
is the same as (1 < 2) < 1
.
So you're checking if the boolean result of 1 < 2
is less than 1
. And the result of 1 < 2
is true
which will be converted to the integer value 1
(false
would become 0
).
In other words, 1 < 2 < 1
is transformed into 1 < 1
which is false
.