I think the "while" condition should actually be
while ((days > 365 && !IsLeapYear(year)) || (days > 366 && IsLeapYear(year)))
And then the inner "if" condition can be eliminated. Thus the final code could be:
while ((days > 365 && !IsLeapYear(year)) || (days > 366 && IsLeapYear(year))) { if (IsLeapYear(year)) days -= 366; else days -= 365; year += 1; }
Edit: if you want to get ternary-operator fancy:
while (days > (IsLeapYear(year) ? 366 : 365)) { days -= IsLeapYear(year) ? 366 : 365; year += 1; }
days_in_year = IsLeapYear(year) ? 366 : 365; while (days > days_in_year) { days -= days_in_year; year += 1; }
#define diy(y) (IsLeapYear(y) ? 366 : 355)
while (days > diy(year)) { days -= diy(year); year += 1; }
But I wouldn't do it with a define but rather:
while (days > (days_in_year = IsLeapYear(year) ? 366 : 365)) { days -= days_in_year; year += 1; }
for (;;) { int days_in_year = IsLeapYear(year) ? 366 : 365; if (days <= days_in_year) break; days -= days_in_year; year += 1; }
I think the "while" condition should actually be
(or perhaps some simplification that I'm too lazy to figure out right now)And then the inner "if" condition can be eliminated. Thus the final code could be:
This seems logical and easier to understand than the original too.Edit: if you want to get ternary-operator fancy: