Search code examples
cansi-c

Variable definition with condition without ternary operator


I just don't know what this line means.:

a = b%4 == 0 && b%100 != 0 || b%400 == 0;

Solution

  • This expression would be more readable with extra parentheses:

    a = ((b % 4 == 0) && (b % 100 != 0)) || (b % 400 == 0);
    

    It is a test for leap year in the Gregorian calendar:

    b is a leap year if it is a multiple of 4, except if it is a multiple of 100, or if it is a multiple of 400.

    As as example: 2016 is a leap year, 2000 was too, but 1900 was not and 2100 will not be a leap year.

    The || and && operators are shortcut logical operators, for respectively OR and AND conditions. The expression is equivalent to this:

    if (b % 4 == 0) {
        if (b % 100 != 0) {
            a = 1;
        } else {
            a = 0;
        }
    } else {
        if (b % 400 == 0) {
            a = 1;
        } else {
            a = 0;
        }
    }