←back to thread

420 points gnabgib | 2 comments | | HN request time: 0.438s | source
Show context
divbzero ◴[] No.44001929[source]
> Note that modern compilers like gcc or clang will produce something like is_leap_year2 from is_leap_year1, so there is not much point in doing this in C source, but it might be useful in other programming languages.

The optimizations that compilers can achieve kind of amaze me.

Indeed, the latest version of cal from util-linux keeps it simple in the C source:

  return ( !(year % 4) && (year % 100) ) || !(year % 400);
https://github.com/util-linux/util-linux/blob/v2.41/misc-uti...
replies(2): >>44002936 #>>44003470 #
1. sigmoid10 ◴[] No.44002936[source]
I like how the linux one is also easier to understand because it doesn't perform three sequential checks which actually invert the last two conditions plus a default return. That's the kind of stuff that can make you crazy if you ever have to debug it.
replies(1): >>44003121 #
2. darkwater ◴[] No.44003121[source]
I wondered 3 minutes "this is not right" til I realized that

  if ((y % 25) != 0) return true;
was actually checking for different from 0 (which in hindsight makes also sense because the century years by default are not leap unless they divide by 400)