desertSniper87
desertSniper87

Reputation: 890

Equal sign/Assignment Operator inside statement

I was browsing github the other day and found this piece of code in C++.

order[i]= order[i]+order[r]-(order[r]=order[i]);

Why is there 2 equal signs in a line of code? I have never seen this before.

Upvotes: 2

Views: 362

Answers (2)

Cloud
Cloud

Reputation: 19323

The assignment operator = returns an LVALUE, meaning a value can be further assigned to it.

Further, this is poor coding in general, as it's hideous. The author would be better off doing separate assignments over multiple lines, as it's easier to read, less prone to errors while implementing (as an extension of readability), the optimizer will likely generate similar code in either case, etc. Also, this kind of code often leads to a common duplicate question on SO: sequence points, and why this code is horrible.

Edit: And as others have pointed out, it invokes UB. Axe it.

Upvotes: 1

Christophe
Christophe

Reputation: 73500

In C and C++ the assignment operator is just an operator like any other. It returns the object on the left side of the assignment.

So the parentheses at the end copy order[i] into order[r] and uses then order[r] with its new value.

Very important remark: The result of this expression is undetermined: it is not guaranteed that the operands of the operator are evaluated from left to right lke in some other languages. It is then compiler dependent, if the second term uses order[r] before or after the assignment in the third term. So there are 2 possible results.

Upvotes: 1

Related Questions