From the standard (section 6.5.16.2, clause 3):
A compound assignment of the form E1 op = E2 differs from a simple assignment expression * E1 = E1 > op (E2) only in the sense that the lvalue E1 is evaluated only once.
That is, if instead you do
*a += 1
it will only locate the target once, not twice. For "simple" variables, as in your example, this may not greatly affect. Of course, if the compiler knows that there is no need to do this twice, it can still optimize and do it once. If there are other objects that can change the pointer (for example, another thread), there is a real difference.
EDIT: Perhaps the best example is something weird, like the following (abuse of & b == & a-1 in my case):
int a, b, *p; a = 1; b = 5; p = &a; *p += (--p == &b) ? 1 : 0; printf("%d %d\n",a,b); // prints 1 6, because --p happens first, then *p a = 1; b = 5; p = &a; *p = *p + ((--p == &b) ? 1 : 0); printf("%d %d\n",a,b); // prints 1 2, because the second *p is evaluated first, // then --p and then the first *p
mweerden
source share