What does the assignment operator mean in return statements, for example return t = ...?

My question is, what does returning an assignment expression mean, as in my code example? I have an enumeration and I redefine the ++: operator. Therefore, in my short example, you can switch between leagues, but in the code I do not understand. The code compiles and works fine.

the 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; } 

Which means "return t = Traficlight :: yellow", why I can not return "Traficlight :: yellow".

+6
source share
4 answers

In return statements, the operator assigns t , which is the link (modifies it), then returns the value.

What the increment operator does: modifies and returns the link at the same time, so that an extra value can be used in another operation.

+5
source

t = Traficlight::yellow writes Traficlight::yellow to t . The result of this expression is also Traficlight::yellow , so this is:

 return t = Traficlight::yellow; 

equally:

 t = Traficlight::yellow; return t; 

In the above function, a reference to t was received as an argument, so changing the value of t really relevant.

+3
source

Your function receives the argument by reference:

 Traficlight& operator++(Traficlight& t) 

And this is a ++ operator, so semantically it should increase its operand, and then return a reference to this operand. So you have to do two things:

 // Assign new value to the t t = Traficlight::yellow; // Return rusult return t; 

This can be written on one line because the assignment operator returns the assigned value.

+2
source

It assigns the value to the variable t (and in your code, t is a reference type, so the change is visible outside), and then returns the value of the variable t .

0
source

All Articles