Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a compound assignment operator for a = b <operator> a (where <operator> is not commutative)?

In a lot of languages a = a + b can be written as a += b In case of numerical operations, a + b is same as b + a, so the single compound operator suffices.

Also, a = a - b can be written as a -=b .

However, a-b is not equal to b-a. Hence, the compound assignment operator does not work for a = b - a

So, are there compound assignment operators for the operation a = b op a (where op can be +, -, *, /, %, and order matters) ?

[Non commutative operations]

like image 527
asheeshr Avatar asked Nov 12 '12 17:11

asheeshr


People also ask

What is difference between assignment operator and compound operators?

The assignment statement stores a value in a variable. Compound assignment combines assignment with another operator.

What is compound assignment operator explain with examples?

The compound-assignment operators combine the simple-assignment operator with another binary operator. Compound-assignment operators perform the operation specified by the additional operator, then assign the result to the left operand. For example, a compound-assignment expression such as. expression1 += expression2.


1 Answers

No there isn't a short-hand notation for a = b + a. If you need to do a lot of a = b + a for strings, you'd better build a list like:

lst = []

...

lst.append("a")
lst.append("bb")
lst.append("ccc")
lst.append("dddd")

...

lst.reverse()

return ''.join(lst)   # "ddddcccbba"
like image 165
kennytm Avatar answered Nov 02 '22 05:11

kennytm