Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+= Operator in C++

Tags:

c++

operators

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 ?

like image 771
Itban Saeed Avatar asked Dec 25 '15 19:12

Itban Saeed


2 Answers

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).

like image 166
Some programmer dude Avatar answered Sep 28 '22 04:09

Some programmer dude


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 classs, the actual operators will be called and it's up to the implementer of those classs to make sense of it all. In these cases ++ and += can be optimal.

like image 22
Paul Evans Avatar answered Sep 28 '22 05:09

Paul Evans