9

These operands may be simple but the difficulty of finding explanations which are definitive and complete prompted me to ask. What are the character combinations containing an operand followed by an equal sign (such as *=, -=,+=, etc), what do they do and how are they useful (especially pertaining to non-numeric fields)?

Examples as well as definitions would be greatly appreciated.

Thanks

6
  • 3
    And Wikipedia doesn't help? en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B Commented Jul 27, 2010 at 15:49
  • These operators appear in many languages, but please pick just one to ask about so we can give better answers and avoid tag spam. Commented Jul 27, 2010 at 15:51
  • Any and all of this information can be easily found on wikipedia or other reference sites. Commented Jul 27, 2010 at 15:51
  • Wiki doesn't really give the greatest examples and offer scope. I narrowed it to c# and am curious to see the capabilities of these operators "( especially pertaining to non-numeric fields)". Commented Jul 27, 2010 at 15:56
  • 3
    Why is everyone jumping all over him for asking? He isn't sure what they do, which makes it difficult to Google. On top of that have you ever tried Googling -= or *=? Commented Jul 27, 2010 at 16:01

8 Answers 8

11

They are usually interpreted broadly as:

x += y === x = x + y 

(etc for your choice of operator)

however; some languages allow you to have a bespoke += operator*, or may interpret it differently in some scenarios; for example, in C# events, += and -= mean "subscribe via the add accessor" and "unsubscribe via the remove accessor" respectively.

Typically they are just space savers, but there can be semantic differences in some cases.


*=where I mean: very different to just the + operator and assignment

Sign up to request clarification or add additional context in comments.

Comments

11

Pretty much all the answers here state that x += y; is "equivalent" to "x = x + y;".

This is not actually true. They are not exactly equivalent for several reasons.

First, side effects are only performed once. Suppose you have

class C { public string S { get; set; } } class D { private static C c = new C(); static C M() { Console.WriteLine("hello!"); return c; } } 

The first line below prints "hello" once, as you would expect. The second prints it twice.

D.M().S += "abc"; D.M().S = D.M().S + "abc"; 

Second, the type system works differently for compound assignment than for regular assignment.

short b = 1; short c = 2; b += c; b = b + c; 

The third line is legal. The fourth line is not; a short plus a short is an int in C#, so b = b + c is an illegal assigning of an int to a short. In this case the compound assignment is actually equivalent to b = (short)(b + c);

If this subject interests you I encourage you to read sections 7.17.2 and 7.17.3 of the C# specification.

3 Comments

"side effects are only performed once". Why is this so (besides that it is written in the spec)? Isn't this a design flaw? Because of this, classes which overload '+' can, under certain circumstances not be used in conjunction with '+='? But the author of the class has no way of preventing the user from doing so anyway... So, if += is not "identical" to +, we at least should get the chance to overload it (partially).
@user492238: No, it is not a design flaw. I think most users would expect that GetDatabaseRecord().TotalPrice += newTaxes; only calls GetDatabaseRecord once. It would be a design flaw to call it twice.
@user492238: As for your second question, I do not understand it. Can you give an example of where x = x + y and x += y should have different semantics? I would say that a type that has a difference between regular addition and compound assignment addition has some design problems. It would be very surprising to me.
2

The great advantage is that you can say:

x += y; 

Instead of the more verbose:

x = x + y; 

Sometimes this is nice when working with strings, as you can use += to append text to an existing string.

2 Comments

Just a note, that using += on strings should be avoided if there are multiple strings to concatenate, as the allocation behavior is very inefficient.
Absolutely. In the case of C#, a StringBuilder would be more appropriate.
2

x += expression is roughly the same thing as x = x + (expression). In other words, it calculates the right-hand side, then applies the + operator to the left-hand side and the result, and then assigns that result back into the left-hand side.

Personally, I'm not a huge fan of them. The /= operator I find a particular menace, as there are many Pascal-related languages that use that to indicate boolean inequality. Someone familiar with that who gets mixed up and tries to use it in C ends up with compiling code that produces some of the most bizzare bugs imagineable.

However, they do come in quite handy when the left-hand side is kind of large, so repeating it would throw out more noise than enlightenment.

Comments

1

These are compound assignment operators. For numeric fields, they're defined to add (+=), multiply (*=), and subtract (-=) the value on the right- from the variable on the left, and assign the result to the variable on the left.

However, C++ supports "operator overloading". Meaning, for any given object, the programmer can define what happens if you write x += 12 and x happens to be an object of type Foo rather than an int. This is commonly done for string classes, so if s1 = "All this" you can write s1 += " and more" and the result will be "All this and more".

Comments

1

Say you have x = 5. If you want to add 1 to x, you can do it in many ways:

x = x + 1; x += 1; x++; ++x;

They're all equivalent, and choosing any of those should leave x with 6.

So basically, if you want to multiply, divide, or subtract from x, just change the + operator to what you want.


Sorry, I didn't see that you mentioned non-numeric fields. In C# and in C++, you can do something called an "operator overload" to give a non-numeric object the ability to utilize these compound operators with a user-defined function and/or comparison.

For instance, strings are generally treated as objects and not as primitive data types, but if you execute String s = "hello"; s += "!";, you'll see that s will contain hello!. That's because the String object has an overloaded operator for += that applies an append with the rvalue ("!"--right of the += operator) to the lvalue ("hello"--left of the += operator).

A related question on C# operator overloading: Simple way to overload compound assignment operator in C#?

2 Comments

It is important to note that x++ and ++x are different, especially in the context of loops.
x++ and ++x not not equivalent although the will eventually end up having the same effect.
1

If you want an explanation try reading http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Compound-assignment_operators like someone already suggested, basically a += b; is equivalent to a = a + b;. It's shorthand to make your code easier to write and read.

Here are some examples:

/* Print all evens from 0 through 20 */ for(i = 0; i <= 20; i += 2){ printf("%d\n", i); } /* Slow down at a linear pace */ /* Stop after speed is 0.1 or less */ while(speed > 0.1){ speed /= 1.2; } speed = 0; 

Those should explain it. It applies to bitwise operations as well as arithmetic, but I can't think of any simple uses off the top of my head and I don't want to confuse you. There's the old temp-less swap trick - a ^= b ^= a ^= b; - which will swap the values of a and b without you having to create a temporary variable, but I'm not sure if you know what the bitwise XOR operation is at this point, so don't read into it yet.

Comments

0

With regard to non-numeric fields: what the operators do is completely arbitrary. In C/++/#, you can override what an operator does, allowing you to write something like:

MyObj += MyOtherObj; // MyObj is now null 

When overloading the operators, you can really do whatever you like.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.