Someone please tell me the difference between the following codes which add two variables of datatype int
. I want to know which one is better.
Code A:
sum = sum + value;
Code B:
sum += value;
We usually prefer ++
operator over += 1
. Is there any specific reason behind that as well ?
I want to know the difference between the above codes with respect to the conventions or efficiency level. Which one is recommended ?
While the end result of the e.g. someVar++
operator is the same as someVar += 1
there are other things playing in as well.
Lets take a simple statement like
foo = bar++;
It's actually equivalent (but not equal) to
temp = bar;
bar += 1;
foo = temp;
As for the prefix and suffix increment or decrement operators, they have different operator precedence, which will affect things like pointer arithmetic using those operators.
As for the difference between
foo += 1;
and
foo = foo + 1;
there's no different for primitive types (like int
or float
) or pointer types, but there's a very big difference if foo
is an object with operator overloading. Then
foo += 1;
is equal to
foo.operator+=(1);
while
foo = foo + 1;
is equal to
temp = foo.operator+(1);
foo.operator=(temp);
Semantically a very big difference. Practically too, especially if any of the operator overload functions have side-effects, or if the copy-constructor or destructor have some side-effects (or you forget the rules of three, five or zero).
One calls operators =
and +
the later calls operator +=
.
operators ++
and +=
are preferred because of readability - most programmers know what they mean.
On the other hand most modern compilers will generate the same code for += 1
as ++
and +
/=
as +=
for builtin types;
But for user defined class
s, the actual operators will be called and it's up to the implementer of those class
s to make sense of it all. In these cases ++
and +=
can be optimal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With