-1

I have recently come across a function which calculates the day of the week for any given date. The function is shown below.

unsigned int getDayOfWeek(const unsigned int day, const unsigned int month, unsigned int year)
{
    static unsigned int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
    year -= month < 3;
    return ( year + year/4 - year/100 + year/400 + t[month-1] + day) % 7;
}

I am having trouble understanding the syntax of year -= month < 3. I am assuming it expands to year = year - (month < 3), however I still cannot understand what this does.

My question is: what does this syntax do in general, not just in the context of this function? For example a -= b < 3.

Thank you in advance.

Tom Hudson
  • 13
  • 4

1 Answers1

1

month < 3 is a boolean expression.

  • false converts to 0
  • true converts to 1.

You might rewrite it as:

if (month < 3) { year = year - 1; }
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • You "might rewrite it as" - I would say "how much clearer it is if it is written as". Unless you are trying to squeeze every ounce of performance out of a tiny processor (8 bit in a wrist watch, or suchlike?) then there is never any need to write such obscure syntax. Good software is all about maintainability and using obscure syntax definitely hinders this. One could argue that a good compiler would produce the same object code for both source code versions – Roger Cigol May 04 '21 at 11:12