Re: AND and OR and parentheses





rick wrote:
> the following line appears in the K&R book in section 5.7:
> leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
> my compiler suggests parentheses "around && within ||"
>
> given that the AND operator has higher precedence than OR, would the
> correct grouping be this:
> leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
> ?

Yes; your parentheses don't change the meaning of the
original. The compiler (presumably) issues the warning
because the people who wrote it felt that this is something
programmers often get wrong.

Oddly enough, in this particular case you *can't* get
it wrong! Consider the other possibility:

leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);

This expression gives the same value to `leap' as the first
(equivalent) pair, even though it arrives at the value by a
different route.

--
Eric.Sosman@xxxxxxx

.



Relevant Pages

  • Re: AND and OR and parentheses
    ... Eric Sosman wrote: ... > rick wrote: ... >> given that the AND operator has higher precedence than OR, ... >> the correct grouping be this: ...
    (comp.lang.c)
  • Re: Parsing a string format
    ... For those of us who are totally lost at this point, ... some of the earlier javascript "scripters" (can't call them programmers) ... Refactoring code to make it leaner and more concise is always ... But that's Rick. ...
    (microsoft.public.vb.winapi)
  • Re: Help in determining age
    ... What I was supposedly thinking about was the 10-day adjustment to the calendar and the new Leap Year calculations that Pope Gregory came up with... ... Rick ... ># Name DOB Inauguration date Inauguration age ...
    (microsoft.public.excel.programming)
  • Re: DateAdd +weeks dropping a few days
    ... (no e-mails, please!) ... Both leap years. ... > Finally, 2014 IS a leap year, but nothing odd happens because we don't ... > Rick B Wrote: ...
    (microsoft.public.access.forms)
  • Re: What things should successful programmers-to-be learn right now?
    ... Rick D. wrote: ... Its a matter of learning how to program. ... Here in silicon valley, we saw mass exodus of programmers, mostly the ... YOU make your programming market. ...
    (comp.programming)

Loading