Dmytro Rudnitskikh Dmytro Rudnitskikh - 14 days ago 5
C++ Question

Nested if-else not working for custom structure c++

I have a custom data structure

date
in C++11:

struct date {
int day;
int month;
int year;
};


I want to compare two
date
s and wrote function for it:

int compare_dates(date a, date b) {
int result = 0;

if (a.year < b.year) {
result = -1;
} else if (a.year == b.year) {
if (a.month < b.month) {
result = -1;
} else if (a.month == b.month) {
if (a.day < a.day) {
result = -1;
} else if (a.day > a.day) {
result = 1;
}
} else {
result = 1;
}
} else {
result = 1;
}

return result;
}


But this function no working correctly. I spent a lot of time to debug it and find some issue in the following part of code:

} else if (a.month == b.month) {
if (a.day < a.day) {
result = -1;
} else if (a.day > a.day) {
result = 1;
}
} else {
result = 1;
}


There are two screenshots during debugging, first on
} else if (a.month == b.month) {
and second when I click next line in debugger. Such happens for all inputs. Why debbuger did not enter into
if (a.day < a.day) {
or
result = 1;
everytime?

Answer

Try with

if (a.day < b.day) {
    result = -1;
} else if (a.day > b.day) {
    result = 1;
}

instead of

if (a.day < a.day) {
    result = -1;
} else if (a.day > a.day) {
    result = 1;
}

The two tests a.day < a.day and a.day > a.day are ever false, so result = -1 and result = 1 are never executed.

I suppose that the compiler optimize the code as follows

} else if (a.month == b.month) {
} else {
  result = 1;
}
Comments