Search code examples
c++enumsreturn

What does assignment operator means in return statements, like return t =...?


I have question: What does it mean to return an assignment expression like in my code example? I have an enum, and I have overridden the ++:operator. So it is possible to switch between lights in my short example - but there is a part in the code I dont understand. The code compiles and work fine.

Code:

enum Traficlight
{green, yellow, red };

Traficlight& operator++(Traficlight& t)
{
    switch (t)
    {
    case green: return t = Traficlight::yellow; //Here <--
    case yellow: return t = Traficlight::red; //Here <--
    case red: return t = Traficlight::green; //Here <--
    default:
        break;
    }
}

int main()
{


    Traficlight Trafic = Traficlight::green;
    Trafic++;

    if (Trafic == Traficlight::yellow)
    {
        cout << "Light is Yellow" << endl;
    }

    string in;

    cin >> in;

}

What does the return t = Traficlight::yellow mean, why can't I just return Traficlight::yellow?


Solution

  • In the return instructions, the operator assigns to t which is a reference (modifies it) then returns the value.

    That's what an incrementation operator does: modifies & returns reference at the same time so the incremented value can be used in another operation.