Pregunta

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");
¿Fue útil?

Solución

>= 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

Otros consejos

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)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top