简体   繁体   中英

Performing arithmetic operations on lvalue

I understood that the following C++ expression

j * 4 = 7; // C2106

is incorrect because an lvalue is expected at the left hand side.

If I guess right, the variable j is infact an lvalue but performing an arithmetic operation j * 4 results in an rvalue. Therefore, is it right to say performing an arithmetic operation like addition on an lvalue will always result in an rvalue ?

If yes, is there any exceptions to this rule?

Note : Let us not consider pointers for this question.

The built-in operators + (unary and binary), - (unary and binary), * (binary), / , % , << , and >> yield prvalues ("pure" rvalues), without exception. (So do various other operators, which you would probably not consider to be arithmetic.) Furthermore, they all require their operands to be prvalues, so if they were originally lvalues, they undergo the implicit lvalue-to-rvalue conversion.

You're probably aware that the built-in compound assignment operators yield lvalues. A less well-known fact is that the built-in preincrement and predecrement operators also yield lvalues. So perhaps they're counterexample to your hypothesis that arithmetic operations always result in rvalues.

If you overload an operator, the value category of its return type can be whatever you wish. You can make operator+ return T& if you want, where T is some class or enum type. Then the result of an addition could be an lvalue. But it's hard to think of when it would ever make sense to write such an operator.

Therefore, is it right to say performing an arithmetic operation like addition on an lvalue will always change it to an rvalue?

Yes. EDIT: Actually, no. See other answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM