Mini Calendar in C - Step 16 logic

I’m trying to understand how the logic example provided in the hint for Step 16’s of the Mini-Calendar project works. Here is the logic:

bool is_leap_year(int year) {
return (year % 4 == 0 && (year % 100 || year % 400 == 0));
}

My question. I understand the left of &&, but the right part confuses me. I understand this to mean one or both of these are true. In determining if a year is a leap year, the year must be divisible by 4 and NOT be divisible by 100 unless it is also divisible by 400. What is the result of year % 100? I know about modulo operator. Shouldn’t this be followed by a result like != 0 for it to be true?

Shouldn’t this be followed by a result like != 0 for it to be true?

Yes its true, but here’s why not adding != 0 also works.

In C++, 0 is evaluated as false, and all other non-zero numbers are evaluated as true.

In the condition, year % 100 != 0 only happens when year is not divisble by 100, thus this returns a non-zero number, and it evaluates to true.

Here you can see this type of conversion.

Hope this helps

Thanks for the explanation. Very helpful. I have not seen in the lesson on logic comparison in the C lessons what you described.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.