Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are assignment operators "required" to return?

Tags:

c++

standards

According to the C++ standard, can I be sure that assignment operators for built-in variables return (the original value)?

Or is this implementation dependent (yet simply have most popular compilers implemented this)?

like image 932
paul23 Avatar asked Nov 14 '11 07:11

paul23


People also ask

What does an 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.

Why do u need a return type for assignment operator?

The return type is important for chaining operations. Consider the following construction: a = b = c; . This should be equal to a = (b = c) , i.e. c should be assigned into b and b into a .

Does the assignment operator return a value in C?

The assignment operators in C and C++ return the value of the variable being assigned to, i.e., their left operand. In your example of a = b , the value of this entire expression is the value that is assigned to a (which is the value of b converted into the type of a ).

What is the purpose of assignment operators?

Assignment operators are used to assign values to variables.


2 Answers

Yes, it is guaranteed:

5.17 Assignment and compound assignment operators

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand.

This applies to built-in types. With user-defined types it can return anything.

like image 127
UncleBens Avatar answered Sep 22 '22 06:09

UncleBens


It depends on what you mean by "the original value".

For example:

#include <iostream>
int main() {
    int i;
    std::cout << (i = 1.9) << "\n";
}

prints 1. The assignment expression yields the new value of the LHS (namely 1), not the "original value" of the RHS (1.9).

I'm not sure whether that's what you meant to ask about.

like image 26
Keith Thompson Avatar answered Sep 24 '22 06:09

Keith Thompson