0

I'm new to programming, so I apologise if this is really basic. I just can't understand the logic of how this expression is evaluated. I know the difference between AND and OR. I'm also aware of short circuiting and precedence. Here is the expression I'm struggling with.

bool a = false
bool b = true
bool c = true

If (a && b || c)
{
    Console.WriteLine("True");
}

This evaluates to true. But I would assume that once it's checked a, it would short circuit because the precedence of && isn't true in its entirety.

Can someone please explain why this is valid?

  • 2
    It's always a good idea to add parentheses on a expression like that, even if they are superfluous. Your reader (/maintainer) shouldn't need to google for the precedence rules when looking at your code in two years. Clarity at the cost of two keystrokes is worth it – Flydog57 Aug 15 '21 at 00:12
  • Regarding short circuiting: The `&&` will short circuit after evaluating `a` as false, so `b` isn't evaluated. But since there's an `||` afterwards, `c` is still evaluated, ultimately returning true. See https://dotnetfiddle.net/92Kfoz – devNull Aug 15 '21 at 00:17
  • That's a great example devNull! Thank you very much. It's clear through your demonstration what the compiler is doing. I was trying to replicate this in VS earlier, but couldn't make sense of it. Can you put this as an answer so I can close the question. – Wayne Griffin Aug 15 '21 at 01:16
  • Depending on the expected result you need to write, even to avoid confusion : `( a && ( b || c ) )` or `( (a && b ) || c )`. [Boolean Algebra for Dummies](https://dev.to/stefandurlesteanu/boolean-algebra-for-dummies-nno) • [What is Boolean Logic?](https://www.lotame.com/what-is-boolean-logic/) • [Boolean logic](https://www.bbc.co.uk/bitesize/guides/zqp9kqt/revision/1) • [Boolean Logic](https://introcs.cs.princeton.edu/java/71boolean/) • [Boolean algebra](https://en.wikipedia.org/wiki/Boolean_algebra) –  Aug 15 '21 at 04:53

2 Answers2

4

&& binds tighter than ||. So a && b || c is equivalent to (a && b) || c.

For the precedence of all operators in C# see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators

Mitch
  • 3,342
  • 2
  • 21
  • 31
-1

It evalutes like this:

First: a AND b resulting in true OR false = (a && b)

Second: true OR false (from First step) OR true = (a && b) || c

since you had a true on the right side of the OR it is TRUE

Soios
  • 27
  • 1
  • 7