3

I have a condition like:

 if (!(InRange1 || InRange2 || InRange3))
{
//Do Something
}

Each of the InRange Variables are boolean.

The desired behavior is if anyone of those values is False I want to do something, but it is not working that way. All of the values have to be false before the event is triggered.

Does it need to be written as

if (!InRange1 || !InRange2 || !InRange3)
{
//do something
}

And, in either case I'm curious why the original statement doesn't work.

bairdmar
  • 113
  • 1
  • 2
  • 10
  • 2
    Did you try it the second way? Did it work? If it worked, that's the right way. If you didn't try it, try it. The original statement failed because it does exactly what it says: `x = (a || b || c); return not x;`. Always break complicated expressions down into separate lines, they're much easier to get your head around that way. (the alternative is memorizing the camel-cased names of dead logicians, which is not a profitable use of your time) – 15ee8f99-57ff-4f92-890c-b56153 Sep 19 '16 at 19:06
  • 3
    Well yes - your first snippet is basically "find out if any of them is true, and invert that result". It's very important to understand *why* that is. Look at the expression `(InRange1 || InRange2 || InRange3)`... what do you expect the result of that to be in various cases? Then remember that you're inverting it with the `!`... but you're inverting the whole result. – Jon Skeet Sep 19 '16 at 19:06
  • When you put `!` in front of parenthesis like that, you are saying `negate everything that is inside the parenthesis`. So anything in those parenthesis that was `true` becomes `false` and vice versa. – Lews Therin Sep 19 '16 at 19:08
  • Other related question: [Reverse the logic of two “or” statements in JavaScript if query](http://stackoverflow.com/questions/22967064/reverse-the-logic-of-two-or-statements-in-javascript-if-query) (that’s about JavaScript but the boolean logic is the same) – poke Sep 19 '16 at 19:11
  • These descriptions make perfect sense. Thanks for clarifying. – bairdmar Sep 19 '16 at 19:14

2 Answers2

12

You can use DeMorgan's Law for this.

What you have is equivalent to NOR. !(A | B | C) is equivalent to !A & !B & !C by DeMorgan's Law.

What you want is NAND, so !(A && B && C). This is exactly equivalent to what you're looking for - !A | !B | !C.

4

Your second assumption is right.

Have a look at boolean algebra and De Morgan's law.

You can either write it not(A) OR not(B) or not(C), or, not(A AND B AND C).

So

if (!(InRange1 && InRange2 && InRange3))
{
    //Do Something
}

and

if (!InRange1 || !InRange2 || InRange3)
{
    //Do Something
}

are equivalent.

Markus Weninger
  • 11,931
  • 7
  • 64
  • 137