我在C++ 11有一個自定義的數據結構date
:嵌套的if-else不工作的自定義結構C++
struct date {
int day;
int month;
int year;
};
我想比較兩個date
S和爲它編寫函數:
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;
}
但此功能無法正常工作。我花了很多時間來調試它,發現下面的代碼部分的一些問題:
} else if (a.month == b.month) {
if (a.day < a.day) {
result = -1;
} else if (a.day > a.day) {
result = 1;
}
} else {
result = 1;
}
有調試期間兩個截圖,first上} else if (a.month == b.month) {
和second當我點擊調試器下一行。這發生在所有輸入上。爲什麼debbuger每次都沒有輸入if (a.day < a.day) {
或result = 1;
?
你可能在其他地方有未定義的行爲,這可能會導致各種奇怪的事情。錯誤不能由您向我們展示的部分複製。請發佈完整的代碼。請參閱http://stackoverflow.com/help/mcve –
感謝@ChristianHackl的評論,下次我將根據* mcve *標準添加代碼。 –