Home > Software design >  Specifying a range inside an if condition in C language
Specifying a range inside an if condition in C language

Time:07-08

I just want to know the difference between these C code segments. I used it in two different ways and final output was not same.

if(120<=units<160){
    
    total= total- total*(15.0/100);
    printf("Revenue : %.2f", total);
    
}


if(120<=units && units<160){
    
    total= total- total*(15.0/100);
    printf("Revenue : %.2f", total);
    
}

Can't we use "120<=units<160" to specify a range in C language?

CodePudding user response:

No, you can't test ranges in this way. What's happening here is the operators are evaluated left-to-right as per operator precedence.

So this means: (120 <= units) < 160

The value of 120 <= units will be 0 if it is false or 1 if it is true

In other words, the full expression will always be true, because both 0 and 1 are less than 160.

CodePudding user response:

The question is similar to a post in C . You can refer to the post in the link below. https://stackoverflow.com/a/3831148/19395482

By Matthieu M.:

Consider the single statement: bool result = 18 < age < 30; We want to evaluate the right-hand expression: 18 < age < 30

There are two operators in this expression, and since they are identical, they both have the same priority, in this case, they are thus evaluated from left to right, therefore the expression is equivalent to:

(18 < age) < 30

So let's first examine the left-hand member: 18 < age, it yields a boolean which is either true or false, typically represented as an integral value respectively 1 or 0. Thus the expression can be summed up as:

{0,1} < 30

which is always true.

Therefore, should you use assert(18 < age < 30); it would never backfire.

CodePudding user response:

It's parsed as one of these two (I don't remember which):

  • (120 <= units) < 160
  • 120 <= (units < 160)

In both cases, one comparison is done, yielding a "boolean" (0 or 1) which is then compared with the other number, typically leading to a "wrong" result (well, it's perfectly correct, just doesn't match your expectation)

  • Related