Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of using compound assignment

What is the real advantage of using compound assignment in C/C++ (or may be applicable to many other programming languages as well)?

#include <stdio.h>

int main()
{
    int exp1=20;
    int b=10;
   // exp1=exp1+b;
    exp1+=b;

    return 0;
};

I looked at few links like microsoft site, SO post1, SO Post2 . But the advantage says exp1 is evaluated only once in case of compound statement. How exp1 is really evaluated twice in first case? I understand that current value of exp1 is read first and then new value is added. Updated value is written back to the same location. How this really happens at lower level in case of compound statement? I tried to compare assembly code of two cases, but I did not see any difference between them.

like image 809
Rajesh Avatar asked Jan 02 '23 12:01

Rajesh


1 Answers

For simple expressions involving ordinary variables, the difference between

a = a + b;

and

a += b;

is syntactical only. The two expressions will behave exactly the same, and might well generate identical assembly code. (You're right; in this case it doesn't even make much sense to ask whether a is evaluated once or twice.)

Where it gets interesting is when the left-hand side of the assignment is an expression involving side effects. So if you have something like

*p++ = *p++ + 1;

versus

*p++ += 1;

it makes much more of a difference! The former tries to increment p twice (and is therefore undefined). But the latter evaluates p++ precisely once, and is well-defined.

As others have mentioned, there are also advantages of notational convenience and readability. If you have

variable1->field2[variable1->field3] = variable1->field2[variable2->field3] + 2;

it can be hard to spot the bug. But if you use

variable1->field2[variable1->field3] += 2;

it's impossible to even have that bug, and a later reader doesn't have to scrutinize the terms to rule out the possibility.

A minor advantage is that it can save you a pair of parentheses (or from a bug if you leave those parentheses out). Consider:

x *= i + 1;         /* straightforward */
x = x * (i + 1);    /* longwinded */
x = x * i + 1;      /* buggy */

Finally (thanks to Jens Gustedt for reminding me of this), we have to go back and think a little more carefully about what we meant when we said "Where it gets interesting is when the left-hand side of the assignment is an expression involving side effects." Normally, we think of modifications as being side effects, and accesses as being "free". But for variables qualified as volatile (or, in C11, as _Atomic), an access counts as an interesting side effect, too. So if variable a has one of those qualifiers, a = a + b is not a "simple expression involving ordinary variables", and it may not be so identical to a += b, after all.

like image 80
Steve Summit Avatar answered Jan 05 '23 17:01

Steve Summit