Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: What does if(a<b<c) do? [duplicate]

Tags:

c

why does the following if-statement return 1 (true)?

int main() {
    short a = 1;
    short b = 5;
    short c = 4;

    if (a<b<c)
        printf("true \n");
    else
        printf("false \n");

    return 0;
}

It is obviously not the same as

if(a<b && b<c)

because this returns false.

Thank you

like image 570
Stockfish Avatar asked Dec 29 '25 04:12

Stockfish


2 Answers

The relational operators (<, <=, >, >=) are read from left to right (and have the same precedence) as you can see here: Operator precedence. Therefore

a < b

is evaluated first. The result of this evaluation (true or false then) will take part in the next evaluation

(1 or 0) < c

Essentially your code is the same as

 if ((a<b)<c)
like image 81
hat Avatar answered Dec 31 '25 19:12

hat


The < operator has left-to-right associativity. So your expression is parsed as follows:

(a<b)<c

So a<b is first evaluated. Since a is less that b it evaluates to true, i.e. 1. So now you have:

1<c

Since c is 4 this is also true, so the final result is 1.

like image 24
dbush Avatar answered Dec 31 '25 18:12

dbush