0

Can someone explain why the below loop in main() does not terminate

#include <iostream>

enum day {
Sunday,     // 0
Monday,     // 1
Tuesday,    // 2
Wednesday,  // 3
Thursday,   // 4
Friday,     // 5
Saturday,   // 6
not_a_day   // 7
};

day operator++(day d) {
    d = (day)(d + 1);
    return d;
}

int main() {
    day d;
    d = Sunday;
    while (d <= Saturday) {
        ++d;
    }
    std::cout << d << std::endl;
    return 0;
}

When I change the overloaded operator to use references, it works as expected, returning 7.

day &operator++(day &d) {
    d = (day)(d + 1);
    return d;
}

Example taken from here.

I also do not understand why the compiler is able to cast day to an int with the + operator, but is not able to do so for ++?

clicky
  • 865
  • 2
  • 14
  • 31
  • 1
    Your overloaded operator has no side effects; it leaves its operand unchanged. As written, `++d` is a no-op. Read about passing by reference in your favorite C++ textbook. – Igor Tandetnik May 02 '17 at 13:17
  • thanks, that resolved with `d=++d`. – clicky May 02 '17 at 13:19
  • If you follow your linked tutorial you'll see that you need to use `day &operator++ (day &d)` so that you pass a mutable reference. Otherwise you can't edit the original `day`. – nitronoid May 02 '17 at 13:19

0 Answers0