0

I have the following snippet of code:

#include <stdio.h>

int main(void) {
    int x=3, y=4, z=6;

    if (x < y < z) {
        z = z+1;
        printf("This if statement got hit. Value of z is %d\n", z);
    }

    if (z > y > x) {
        printf("This if statement got hit. Value of z is %d", z);
        z = z+2;
    }

    printf("Values: x=%d y=%d z=%d\n", x, y, z);
}

The first if statement evaluates to true, as I expect. z is incremented. However, the second if statement does not evaluate to be true. It seems to me that the logic is reversed and that the condition should also be evaluated to true. The final printf outputs Values: x=3 y=4 z=7. I was expecting Values: x=3 y=4 z=9.

Is anyone able to shed some light on why this is so?

Cheers.

Dave Cooper
  • 10,494
  • 4
  • 30
  • 50

1 Answers1

4

It's evaluated left to right. You could have written: (x < y) < z and (z > x) > y.

(x < y) evaluates to 0 or 1, if false or true. This is then compared to the value of z.

To get what you want, you should write:

if ((x > y) && (y > z))

and

if ((z < y) && (y < x))

ThomasH
  • 1,085
  • 10
  • 12