13

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 ?

Itban Saeed
  • 1,660
  • 5
  • 25
  • 38

10 Answers10

17

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

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
14

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.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • but in my case both do the same at the end. which method would you recommend ? – Itban Saeed Dec 25 '15 at 19:56
  • 3
    @ItbanSaeed Your original post did not mention what types `sum` and `value` are. That's why there is no concrete answer as to what is recommended. If they are user-defined types and `+` or `+=` are overloaded, then it's up to you to decide what is efficient by looking at the source for these overloads and doing tests. And no, doing a `+1` does not determine if those are `ints`. Someone could easily come up with a `big_int` class that takes an `int` as a parameter in the overloaded `+` or `+=`. – PaulMcKenzie Dec 25 '15 at 20:05
  • @PaulMcKenzie I am sorry for the misunderstanding. Thanks for the correction :) – Itban Saeed Dec 25 '15 at 20:16
7

cout << sum++; Would print out the value of sum before it was incremented. Also, depending on what you are doing, you can overwrite the operators += and +.

Pétur Ingi Egilsson
  • 4,368
  • 5
  • 44
  • 72
6

When you minimize code, you reduce the chance of an error (a typographical error or a logical error).

By using

sum += value;

you reduce the chance - ever so slightly - of an error while typing

sum = sum + value;

The same with value++;

value += 1;

could be more easily confused with

value += l; where l is a variable....

Its more about consistency that it is about right or wrong, but reducing code is a major bonus for maintainability.

Care must be taken with precendence of operators however, in complex statements.

Grantly
  • 2,546
  • 2
  • 21
  • 31
5

In the case shown there's no particular reason to prefer one method of incrementing the value over another except perhaps for readability purposes. In this case I think I'd prefer sum += value over sum = sum + value as it's a bit briefer and (I think) clearer, but YMMV on that.

As far as prefering ++ over += 1, (IMO again) ++ is preferable when incrementing a value as part of an expression, e.g. sum += array[index++] - but if the entire point of what's being done is adding one to a value I'd prefer index += 1. But let's face it, a great deal of this is personal preference and spur-of-the-moment choice. I always try to write what I think, at that moment, is the simplest and clearest code possible - but I must admit that when I go back and read some of my own code later I have more "What was I thinkin'?!?" moments than I'd care to admit to. :-)

YMMV.

Best of luck.

  • thanks for this nice explanation, but in my opinion `sum = sum + value` looks more readable instead of `sum += value` so why should I use `sum += value` moreover, **can you please relate it with efficiency or standard conventions ?** I agree that one should write what he thinks but let us suppose that we have to justify each and every statement of our code so how would you justify `sum += value` since (IMO) it less readable than `sum = sum + value`. – Itban Saeed Dec 25 '15 at 20:08
  • 2
    @ItbanSaeed operator `+=` for a *well-written* user defined type is more efficient than using `operator +`. The reason is that `+` creates a brand new object, while `+=` works with the existing object. But note -- *well written*. – PaulMcKenzie Dec 25 '15 at 20:17
  • 1
    @ItbanSaeed - I agree with what PaulMcKenzie wrote in his comment regarding the C++ issues surrounding user-written types/classes. To my eye `sum += value` is easier to read because there's fewer tokens to (mentally) parse - but again, that's a matter of personal preference and habit. If justification is needed, my "justification" is that, for me, it's easier and quicker to comprehend than `sum = sum + value` - but then, I've been writing C and it's derivatives for over 30 years (my, where *does* the time go? :-) so perhaps it's just that my habits have pretty much atrophied. Again - YMMV. – Bob Jarvis - Слава Україні Dec 25 '15 at 20:22
4

Code A and B do the same thing. The advantage to using Code B is that it's quicker to type and easier to read.

As for using the ++ operator over += 1, again it is for readability. Although there is a difference between foo++ and ++foo. The former is read first and then incremented, while the latter is incremented first and then read from.

James Wu
  • 149
  • 3
  • See my comments. It cannot be determined if `A` and `B` do the same thing unless we know exactly what types are being used. – PaulMcKenzie Dec 25 '15 at 20:13
2

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

An example cited from Java's +=, -=, *=, /= compound assignment operators

[...] the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);
Community
  • 1
  • 1
Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256
1

Its basically the same thing. Its both an operator.

One of it calls = and +. And the other +=..

So if you did value +=5. Value goes up by 5. += is better and more organized. And shortens your code whitch is better and more professional.

  • 3
    The OP did not specify what types `sum` and `value` are. So yes, semantically it means "add", but nothing stops an overload of `+` and `+=` from doing something totally inefficient or unorthodox. – PaulMcKenzie Dec 25 '15 at 20:10
1

There is no difference between the two in terms of functionality. A += B actually means A = A + B. The first one is just a shorter way of writing the second.

washington
  • 98
  • 1
  • 7
  • 2
    Just to repeat my other comments -- we don't have enough information to determine if there is a difference or not in functionality. It all depends on what `A` and `B` are and if those operators are overloaded. – PaulMcKenzie Dec 25 '15 at 20:25
1

They both are same up to that, both can be used for incrementing the value of a variable (stored in it).

x++ will increment the value of x by one (1) every run time.

+= adds right operand to the left operand and stores the result in left operand. Something like following: C += A is just same as C = C + A

The difference between both ++ and += is that the first can increment by one (1) only, while += can be used to increment more than one in just one line.

e.g:

x += 1; // will increment by 1 every run time
x += 4; // will increment by 4 every run time
x += 10; // will increment by 10 every run time
Melebius
  • 6,183
  • 4
  • 39
  • 52