1

How does the C process a conditional statement such as n >= 1 <= 10?

I initially thought that it would get evaluated as n >= 1 && 1 <= 10, as it would be evaluated in Python. Since 1 <= 10 is always true, the second porition of the and is redundant (the boolean value of X && True is equivalent to the boolean value of X).

However, when I run it with n=0, the conditional gets evaluated to true. In fact, the conditional always seems to evaluate to true.

This was the example I was looking at:

if (n >= 1 <= 10)
  printf("n is between 1 and 10\n");
Ashwin Balamohan
  • 3,303
  • 2
  • 25
  • 47
  • 6
    And are you asking us to answer the question for you? How will that help you? have you tried compiling it? – Mats Petersson Jul 20 '13 at 21:39
  • 1
    Did you read chapter about operator precedence first? – RiaD Jul 20 '13 at 21:42
  • I believe it isn't legal, I'm pretty sure you'd have to say if( n >= 1 && n <= 10), but don't quote me on that - hence my leaving it as a comment and not the answer. Once you set it up that way, the precedence would be left to right. And I think C and C++ use "lazy" checks, so.. if the left side fails, it won't even bother checking the right side. – Ricky Mutschlechner Jul 20 '13 at 21:43
  • 2
    Duplicate of [this question](http://stackoverflow.com/q/6961643/827263); see [my answer](http://stackoverflow.com/a/6961728/827263). – Keith Thompson Jul 20 '13 at 21:56
  • Question has been reworded to fit the rules – Ashwin Balamohan Nov 14 '13 at 19:19

2 Answers2

11

>= operator is evaluated from left to right, so it is equal to:

if( ( n >= 1 ) <= 10)
    printf("n is between 1 and 10\n");

The first ( n >= 1 ) is evaluated either as true or false, which is equal to either 1 or 0. Then that result of 1 or 0 is compared to result <= 10 which will always evaluate to true. Thus the statement printf("n is between 1 and 10\n"); will always be printed

4

It's evaluated left to right like this:

n = 5;

if (n >= 1 <= 10)
// then
if (1 <= 10)
// then 
if (1)

It first checks if n >= 1. If it is, it evaluates to 1, otherwise 0. This leads to the next evaluation, 1 <= 10, which evaluates to 1 as well. Note that this also succedes:

n = 5;
if (n >= 3 == 1)

Because it's evaluated like this:

n = 5;
if (n >= 3 == 1) // but you should never write code like this
// then
if (1 == 1)
// then
if (1)

Also note why it works with n = 0

n = 0;
if (n >= 1 <= 10)
// then
if (0 <= 10) // 0 isn't greater or equal to 1, so 0 (false) is "returned"
// then
if (1) // but 0 is less than or equal to 10, so it evaluates as 1 (true)
tay10r
  • 4,234
  • 2
  • 24
  • 44