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

user398296
  • 101
  • 1
  • 3
    And Wikipedia doesn't help? http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B – Matthew Jones Jul 27 '10 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. – danben Jul 27 '10 at 15:51
  • Any and all of this information can be easily found on wikipedia or other reference sites. – James Jul 27 '10 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)". – user398296 Jul 27 '10 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 *=? – Mike M. Jul 27 '10 at 16:01
  • @Mike M.: http://www.google.com/search?q=minus+equals+c%23 – Hello71 Aug 07 '10 at 16:34

8 Answers8

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

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
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.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • "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 Mar 03 '11 at 09:31
  • @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. – Eric Lippert Mar 03 '11 at 15:05
  • @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. – Eric Lippert Mar 03 '11 at 15:08
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.

Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
  • 3
    Just a note, that using `+=` on strings should be avoided if there are multiple strings to concatenate, as the allocation behavior is very inefficient. – Dathan Jul 27 '10 at 15:56
  • 1
    Absolutely. In the case of C#, a StringBuilder would be more appropriate. – Justin Ethier Jul 27 '10 at 16:47
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.

T.E.D.
  • 44,016
  • 10
  • 73
  • 134
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#?

Community
  • 1
  • 1
danyim
  • 1,274
  • 10
  • 27
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".

Chris B.
  • 85,731
  • 25
  • 98
  • 139
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.

Vasiliy Sharapov
  • 997
  • 1
  • 8
  • 27
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.

Brian S
  • 4,878
  • 4
  • 27
  • 46