Hacker News new | ask | show | jobs
by susam 2308 days ago
I learnt the following test for leap year early in my software engineering career from the book "The C Programming Language" by Kernighan & Ritchie (see section 2.5 Arithmetic Operators):

  (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
The following test also works:

  year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
1 comments

For those who were curious why these could both work:

(A & B) | C differs from A & (B | C) in two cases: when A is false, C is true, and B is any value.

But in this case in particular, those differences would create a bug when A is false (the year is not divisible by 4) at the same time that C is true (the year _is_ divisible by 400). Since that can't happen, the bug cannot occur.