Niklas Niklas - 1 year ago 83
C++ Question

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 override the ++:operator. So it is possible to switch between ligths in my short example - but there is a part in the code i dont understand. The code compiles and work fine.


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 <--

int main()

Traficlight Trafic = Traficlight::green;

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

string in;

cin >> in;


What does the "return t = Traficlight::yellow" mean, why cant i just return

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download