This is not a problem that needs to be solved but a question to understand C++ code better. I have an assignment that has a class to get a date input where the validation for leap year is a member of. I found many examples online and one stands out as a popular choice. I am going to use it but I have no idea how it works. Using code from other sources does not mean you actually are learning something. My question is can someone explain to me what this code is doing to arrive at the solution for a leap year? Thank you in advance.

// dateType Class function to check for leap year
bool dateType::isleap(int year) const
 if (year%4==0 && year%100!=0 || year%400==0)
    return true;
    return false;

Leap year occurs every 4 years. If the year is evenly divisible by 100 then it is not a leap year, unless it is evenly divisible by 400. For example: the year 2000 was a leap year because it is evenly divisible by 400, but the year 1800 was not a leap year because it is evenly divisible by 100 but not 400. So 1600, 2000 and 2400 are leap years but 1700, 1800, 1900, 2100, 2200 and 2300 are not.

Now, in the function you posted, the && and || operators have the same precedence, so just read from left to right.

Edited 3 Years Ago by Ancient Dragon

Good explanation AD. :-)

Pretty correct. This is code for a Date class that has been validated at many levels:

bool Date::isLeapYear() const
    bool retval = false;
    if (isValid())
        int yr = year();
        retval = ((yr % 4) == 0 && ((yr % 100) != 0 || (yr % 400) == 0));
    return retval;

So, it is basically the same as yours except that you need to properly "scope" the last 2 terms. IE, if ((year%4) == 0 && ((year%100) != 0 || (year%400) == 0))

FWIW, I wrote that code in the early 1990's, about 20 years ago... It also was validated in a full-scale Y2K assessment. :-)

Edited 3 Years Ago by rubberman

Since && and || are the same precedence, technically there is no need for the parentheses. But for human eyes you are right in that the code is more understandable with the parentheses. The two functions should produce the same identical results.

Thank you for the input. I figured it was something simple because it is always the simple stuff that I struggle with.

This question has already been answered. Start a new discussion instead.