Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "+=" and normal addition

Tags:

c

What is the difference in += and normal add

a = a + b;
a += b;

what is the different in above two lines?
Is there any increase in CPU cycles for "+=" operator?
Which would be the preferable method of coding.?

like image 225
sujai M J Avatar asked Oct 21 '25 00:10

sujai M J


2 Answers

Beside single evaluation of first operand, there is second difference, that occurs when b is an expression, involving operators with lower precedence. For instance:

int a = 1;
a += 0 || 1;

yields 2, while:

int a = 1;
a = a + 0 || 1;

stores 1 into a. The equivalent of the former statement would be:

a = a + (0 || 1);
like image 153
Grzegorz Szpetkowski Avatar answered Oct 23 '25 14:10

Grzegorz Szpetkowski


There is a difference in between them and it is explained in the C standard:

C11: 6.5.16.2 Compound assignment (p3):

Acompound assignment of the form E1 op= E2 is equivalent to the simple assignment expression E1 = E1 op (E2), except that the lvalue E1 is evaluated only once, and with respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation.

like image 29
haccks Avatar answered Oct 23 '25 14:10

haccks