Exikle
Exikle

Reputation: 1165

Printf even though it shouldn't

I have this part of an if statement and I'm getting a weird output.

int x = 10;

if(1 < x < 5){
    printf("F\n");
}

Why does it print "F"? Logically isn't the if statement false because x is greater than 1 but not less than 5?

Upvotes: 0

Views: 47

Answers (2)

Lars
Lars

Reputation: 1387

In C, you can't chain comparisons like that. The expression 1 < x < 5 is evaluated as (1 < x) < 5: so for x = 10, the expression is (1 < 10) < 5. (1 < 10) is true, which C represents as the value 1, so the expression reduces to 1 < 5. This is always true, and your printf() if executed.

As level-999999 says, in C you need to explicitly combine single comparisons with && and ||.

Upvotes: 4

level-999999
level-999999

Reputation: 31

If you are using C, you should have broken down the condition into two arguments :

    if ( x > 1 && x < 5) {
        printf("F\n");
    }

Upvotes: 1

Related Questions