Isaac
Isaac

Reputation: 11805

AND OR order of operations

What is the equivalent of this statement?

if(cond1 AND cond2 AND cond3 OR cond4 AND cond5 AND cond6)

Is it

if((cond1 AND cond2 AND cond3) OR (cond4 AND cond5 AND cond6))

Or

if(cond1 AND cond2 AND (cond3 OR cond4) AND cond5 AND cond6)

Or

if(((cond1 AND cond2 AND cond3) OR cond4) AND cond5 AND cond6)

ect...

This has been something that I've always been scared approaching, to which I just surround the conditions in parenthesis ( ). It would be great if my mind could be settled.

Upvotes: 34

Views: 42631

Answers (5)

Veer
Veer

Reputation: 1593

In most languages AND is evaluated first, hence

if((cond1 AND cond2 AND cond3) OR (cond4 AND cond5 AND cond 6))

is the right choice.

For C#, See http://msdn.microsoft.com/en-us/library/aa691323%28v=vs.71%29.aspx

For C, See http://en.cppreference.com/w/cpp/language/operator_precedence

For Java , See http://bmanolov.free.fr/javaoperators.php

Upvotes: 21

Deantwo
Deantwo

Reputation: 1317

A good way to remember this is to think of it mathematically.

  • AND as * (multiply)
  • OR as + (addition)
  • TRUE as 1
  • FALSE as 0

So thinking of it as simple math you get this:

  • 0 * 0 = 0
  • 1 * 0 = 0
  • 1 * 1 = 1
  • 0 + 0 = 0
  • 1 + 0 = 1
  • 1 + 1 = 1

Only thing that may be a tiny bit confusing is 1 + 1 = 1, but a bit can't go above 1. But it makes sense if you think of 1 as any non-zero number.

So with this in mind you can then apply this logic:

if(cond1 AND cond2 AND cond3 OR cond4 AND cond5 AND cond6)

Becomes:

if(cond1 * cond2 * cond3 + cond4 * cond5 * cond6)

See: https://en.wikipedia.org/wiki/Order_of_operations

Upvotes: 84

paxdiablo
paxdiablo

Reputation: 882196

It depends entirely on the language or environment you're asking about, which unfortunately you haven't specified.

AND may have higher precedence over OR, or it may be the other way around, or it may be equal.

It may be evaluated left-to-right, right-to-left or, from the middle outwards in alternating directions if your language is designed by a sadist :-)

It's quite common for AND to have a higher precedence than OR and for them both to be left-to-right associative.

In that case

cond1 AND cond2 AND cond3 OR cond4 AND cond5 AND cond 6

would be equivalent to:

((cond1 AND cond2) AND cond3) OR ((cond4 AND cond5) AND cond 6)

Upvotes: 0

Gian
Gian

Reputation: 13955

In the normal set of boolean connectives (from a logic standpoint), and is higher-precedence than or, so A or B and C is really A or (B and C). Wikipedia lists them in-order. Most programming languages should obey this convention unless they are really weird.

That said, for your particular language or environment it should be possible to concoct a very small test to satisfy yourself that it is one way or the other :)

Upvotes: 4

Monstieur
Monstieur

Reputation: 8112

Most languages evaluate AND first.

Upvotes: 0

Related Questions