Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

enums

return

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.

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 cant i just return "Traficlight::yellow".

like image 404
Niklas Avatar asked Oct 11 '16 18:10

Niklas


People also ask

What is the symbol of assignment operator?

symbols “=” and “<-” are used as the assignment operator.

What does the assignment operator return?

The assignment operators return the value of the object specified by the left operand after the assignment. The resultant type is the type of the left operand. The result of an assignment expression is always an l-value.

What do you mean by assignment operator?

The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.

Which operator is used in assignment statement?

The simple assignment operator ( = ) is used to assign a value to a variable.


2 Answers

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.

like image 180
Jean-François Fabre Avatar answered Oct 14 '22 00:10

Jean-François Fabre


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

return t = Traficlight::yellow;

is equal to:

t = Traficlight::yellow;
return t;

In the function above, reference to t was received as argument, so changing value of t is in fact relevant.

like image 26
zvone Avatar answered Oct 13 '22 23:10

zvone