Is the statement value += i; the exact same as value = value + i?

Other than the extra space in the editor, is there any difference between the two statements?

EDIT: Thanks for the answers. I would also like to know how each statement is evaluated by the compiler.

Upvotes: 0

Views: 112

Answers (4)

Pete Becker
Pete Becker

Reputation: 76438

Even for PODs they're not quite the same; the difference is trivial, but your helpful compiler writer may warn you for the latter but not for the former:

char ch = get_a_character();
++ch;
ch = ch + 1; // narrowing conversion

Upvotes: 0

Robert Cooper
Robert Cooper

Reputation: 1270

Yes, there can be differences. Some objects, such as Forward Iterators, define increment operators (x++ and ++x), but not not operator+=. Some objects, like string, define operator+= but not increment. But, generally, if x += 1, ++x, and x++ are all defined, they will do the same thing.

Upvotes: 0

Zero
Zero

Reputation: 12099

No - for anything other that PODs the operators may be overloaded.

You would hope that any reasonable implementation makes these operations the same, but it is up to the developer and not enforced by the compiler.

You can imagine even more subtle problems when people overload operators such that (A==B) is not the same as (B==A).

Upvotes: 6

Mark Ransom
Mark Ransom

Reputation: 308452

Yes, they are identical. It's highly probable that the compiler will generate the same code for both.

Unless one or both of the operators have been overloaded, of course. This is why some people frown on operator overloading.

Upvotes: -1

Related Questions