0

I'm going through some C# coding exercises and have run into some operator logic that's stumped me.

The following line of code evaluates to false:

int a = 40, int b = 50;

if (a >= 20 && a <= 30 && (b < 20 || b > 30))
    {
       return a;
    }

However, if I remove the brackets from inside the if statement, it evaluates to true.

if (a >= 20 && a <= 30 && b < 20 || b > 30)
     {
            return a;
     }

Can anyone explain what I'm missing? Given that a isn't between 20 and 30, shouldn't it return false? I don't understand why putting the b portion of the if statement in brackets makes it evaluate to false.

Is it evaluating everything prior to "b > 30" as a single condition?

2 Answers2

2

This is all to do with operator precedence.

Just like how * are evaluated first before + (we say * has a higher precedence than +), && is evaluated before ||, as specified.

In the first code snippet, you used brackets to "override" this precedence, making the || part evaluate first, just like how you can add parenthesis to the expression 1 + 2 * 3 to make it evaluate to 9 instead of 7.

a >= 20 && a <= 30 && (b < 20 || b > 30)
                      ^^^^^^^^^^^^^^^^^
                        this part first

which becomes:

a >= 20 && a <= 30 && true
^^^^^^^    ^^^^^^^
now these parts

which becomes:

false && false && true

resulting in false.

In the second example however, there are no parentheses so the expression is evaluated according to the normal precedence rules:

a >= 20 && a <= 30 && b < 20 || b > 30
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This part first

Which becomes:

false || b > 30
         ^^^^^^
         then this

which becomes:

false || true

resulting in true.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

If you look at the second part where you have removed the parenthesis, it is now divided into two subparts.

First one being : a >= 20 && a <= 30 && b < 20 This evaluates to false. First one being : b > 30 This statement evaluates to true.

So at the end you have something like this F || T from both the statements which should eventually give you true as end result

Sakshi Vij
  • 41
  • 4