Calendar Functions (simpler leap year calculation)

Bob Devine devine at vianet.UUCP
Sat Sep 13 06:33:30 AEST 1986


Dave Lewis writes:
> leapyear (year)
> int year;
> {
>   if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
>      return (1);
>   else
>      return (0);
> }

  While this works, it is overkill.  Unless you believe that your
code will make it to the year 2100, a simple test for divisibility
by 4 is sufficient.  If you really want an algorithm for all years,
you then need to also test for years divisible by 4000...

int
leapyear(year)
    int year;
{
    /* works for the years 1901-2099 */
    return(year%4);
}

Or if you want a simple cpp macro:

#define  isleapyear(year)   ((year)%4)

Bob Devine



More information about the Comp.lang.c mailing list