0

I tried the following piece of code in C, it is clearly wrong:

#include <stdio.h>

int main(void)
{
    int i = 0;
    
    for (i = 0; i < 20; ++i)
    {
        if (10 < i < 15) // It should be ((10 < i) && (i < 15))
        {
            printf("## @ i = %d\n", i);
        }
    }

    return 0;
}

Its result is:

## @ i = 0
## @ i = 1
## @ i = 2
## @ i = 3
## @ i = 4
## @ i = 5
## @ i = 6
## @ i = 7
## @ i = 8
## @ i = 9
## @ i = 10
## @ i = 11
## @ i = 12
## @ i = 13
## @ i = 14
## @ i = 15
## @ i = 16
## @ i = 17
## @ i = 18
## @ i = 19

No errors produced by gcc compiler. The result of the if condition is always true.
Why that?

Filippo
  • 126
  • 1
  • 12
  • 1
    Operator associativity for < is left-to-right, so it is parsed as `(10 < i) < 15`. `10 < i` is either evaluated as 0 or 1. Either way, the result is always less than 15 so the expression is always true. See the linked duplicate for details. – Lundin Sep 29 '22 at 07:34
  • Thank you for your explanation. Now it's clear what's happening. However I didn't find a similar post, nice to see it! – Filippo Sep 29 '22 at 07:36

0 Answers0