Search code examples
coperator-precedence

Operator precedence is confusing on long statement


I have worked with a simple C program to find the Day for Given Date. For it, I have written a lot of lines to calculate the day and month and to find the kind of the given year. While Surfing I came to know about a single line code to find the day for the given date. The code is as below

( d += m < 3 ? y --: y- 2, 23 * m / 9 + d + 4 + y / 4 - y / 100 + y / 400) % 7 ;
// 0 - Sunday, 6 - saturday 

It gave the correct answer for all inputs, but I couldn't understand the values used in this expression.

  1. Why the sum of day and month is checked for less than 3.
  2. Why the year is reduced by one and the condition fails it decreases the year by 2.
  3. Why the numbers 3, 23 and 9 are used in this expression.

I have confused about the operator precedence on this statement. Can anyone explain how this works?


Solution

  • What I've found so far: 23 * m / 9 results in

     1  2 3
     2  5 2
     3  7 3
     4 10 2
     5 12 3
     6 15 2
     7 17 3
     8 20 3
     9 23 2
    10 25 3
    11 28 2
    12 30 3
    

    This expression adds the days over 28 days of a month.

    The expression y / 4 - y / 100 + y / 400 results in:

    1995 483 0
    1996 484 1
    1997 484 1
    1998 484 1
    1999 484 1
    2000 485 2
    2001 485 2
    

    with the result, adding one day every 4 years (except leap years)

    Because every year with 365 days (mod 7 == 1) increments the weekday by 1, the years are added to the days.

    The expression d + (m < 3 ? y --: y- 2) is for correcting the leap year calculation. If we have a leap year, we can correct by one day only if we have a month >= march.