Re: Precedence of Logical Operators



Joe Wright wrote:
*** T. Winter wrote:

In article <slrndo15bn.2hge.jmabel@xxxxxxxxxxxxx> Jordan Abel <jmabel@xxxxxxxxxx> writes:
> On 2005-11-20, August Karlstrom <fusionfive@xxxxxxxxx> wrote:
> > Hi,
> > Can someone explain the reason for the warning from GCC below:
> >
> > $ gcc -Wall test.c
> > test.c: In function ‘main’:
> > test.c:8: warning: suggest parentheses around && within ||
> >
> > </shell-session>
> >
> > For sake of consistency, why not suggest parentheses around `y * z' as > > well? (which would be absurd)
> > Logical operators are easier for people to get confused about because
> they are less familiar.


The more so because in mathematics there is *no* precedence between and and
or. But there is between + and * (although many people even get that wrong.)


Way in the mid last century when I was learning computer logic for the first time Boolean algebra expressions looked like 'a * b + c' which meant precisely that '*' was 'and' and '+' was 'or'. Did we all go to different schools together, or what?

It's likely, although I did see this when I learned Boolean logic. Note that '+' is *not* 'or', since 1 + 1 = 10, while 1 or 1 = 1. It makes more sense to "equate" '+' with 'xor' (IIRC, the notation is still used sometimes in electrical engineering). Note that half-adders are built with an 'and' and an 'xor' gate.

This was 1962 at Philco Corporation. The '*' did have precedence and the above from was equivalent to '(a * b) + c'. Our instructor explained the similarities between 'and' and 'mult' and between 'or' and 'add' but they are now lost in the fogs of time.

The precedence here is added by analogy: '*' has precedence over '+', 'and' and 'or' are similar to '*' and '+', ergo.

Of course it's not *wrong*; you can add precedence in any way you like. This convention is simply not used in mathematics, because it's artificial compared to letting '*' take precedence over '+' ('*' is typically defined in terms of '+', so it's a "higher" operator).

De Morgan's laws illustrate it very well:

a && b == !(!a || !b)
a || b == !(!a && !b)

Or if you prefer

!(a && b) == !a || !b
!(a || b) == !a && !b

There is very compelling reason to treat 'and' and 'or' equally in algebraic theory. Adding precedence, as many programming languages do, has the practical advantage of write down some expressions with less parentheses, but it's simply not a universal convention.

S.
.


Loading