mwada
mwada

Reputation: 21

Boolean rules are bugging me

I just encountered a propably simple problem with booleans

If I have an if statement like this one: !(!A && !B) && B, how does it exactly go?

I thought it was the same as A && B (inverts the conditions inside the brackets), but it obviously wasn't.. which is bugging me

So, would someone like to elaborate how it really goes because I think I'm missing something here?

Upvotes: 2

Views: 53

Answers (3)

Roman Dobrovenskii
Roman Dobrovenskii

Reputation: 945

Unfortunately, in general case you cannot use logic identities in programming as you do that at discrete mathematics class.

As it was mentioned by HashPsi and Bas van Stein, from the logical point of view your expression is equivalent to B. In the real world you can have the following code:

def A():
  throw StupidException()

def B():
  return True

!(!A() && !B()) && B() # throws exception
B() # returns True

So technically your expression differs significantly from just B. You can argue that this is very specific example, but in practice most of your functions have some side effects, so in general you can never assume that mathematical logic works for boolean expressions.

As a real-world example where ordering of boolean expressions matters, you can consider a following idiomatic C++ code:

if (foo && foo->bar()) {do something}

The code above would check that foo is not null before calling bar method. If you just rearrange that expression, you'll get a crush:

if (foo->bar() && foo) {do something}

If foo==nullptr, foo->bar will cause termination of program, since foo->bar() will try to be called before check of foo value.

Upvotes: 1

HashPsi
HashPsi

Reputation: 1391

!(!A && !B) = (A || B)

so

!(!A && !B) && B = (A || B) && B = A && B || B = B

The final result is simply B

Upvotes: 1

Niki van Stein
Niki van Stein

Reputation: 10724

!(!A && !B) && B is the sams as (A || B) && B you forgot to invert the and to or. Which in turn btw is just B.

Upvotes: 3

Related Questions