illegal else without matching if

bool isGregorianDate(int month, int day, int year) {
if (year > 1752) {
if (((((month - 1) % 2 == 0) && (month < 8)) || (month >= 8 && month <= 12 && month % 2 == 0)) && (day >= 1 && day <= 31)) {
return true;
}
else if ((month == 4 || month == 6 || month == 9 || month == 11) && (day >= 1 && day <= 30)) {
return true;
}
else {
return false;
}
}

else if ((year == 1752) {
if (month == 9 && day > 13 && day <= 30) {
return true;
}
(line 243) else if ((month == 10 || month == 12) && (day >= 1 && day <= 31)) {
return true;
}
else if ((month == 11) && (day >= 1 && day <= 30)){
return true;
}
else {
return false;
}
}

I get an "illegal else without matching if" at line 243. What is the problem, and what do i do?
This is what you've written, you tell us what's wrong.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
bool isGregorianDate(int month, int day, int year) {
    if (year > 1752) {
        if (((((month - 1) % 2 == 0) && (month < 8)) || (month >= 8 && month <= 12 && month % 2 == 0)) && (day >= 1 && day <= 31)) {
            return true;
        }
        else if ((month == 4 || month == 6 || month == 9 || month == 11) && (day >= 1 && day <= 30)) {
            return true;
        }
        else {
            return false;
        }
    }

    else if ((year == 1752) {
        if (month == 9 && day > 13 && day <= 30) {
            return true;
        }
        (line 243) else if ((month == 10 || month == 12) && (day >= 1 && day <= 31)) {
            return true;
        }
        else if ((month == 11) && (day >= 1 && day <= 30)){
            return true;
        }
        else {
            return false;
        }
    }
Last edited on
You have an extra open parenthesis on the line that says else if ((year == 1752) {

You could perhaps simplify it with an array of month lengths. And you could take leap years into account (although I don't know if they work the same back in the 1750's).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>

bool isLeapYear(int y) {
    return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
}

bool isGregorianDate(int year, int month, int day) {
    static int days_in_month[] = {
        // J   F   M   A   M   J   J   A   S   O   N   D
        0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };

    if (month < 1 || month > 12 || day < 1 || year < 1752)
        return false;

    if (month == 2)
        days_in_month[2] = isLeapYear(year) ? 29 : 28;

    if (day > days_in_month[month])
        return false;

    if (year == 1752 && (month < 9 || (month == 9 && day < 14)))
        return false;

    return true;
}

int main() {
    while (true) {
        std::cout << "year month day: ";
        int y, m, d;
        std::cin >> y >> m >> d;
        std::cout << isGregorianDate(y, m, d) << '\n';
    }
}

Topic archived. No new replies allowed.