Assignment Operators

The assignment operators are the last general group of operators. Plain assignment (=) is the most obvious one. From one point of view it makes no sense to think of it as calculating any kind of expression, since usually it's just used to copy a value into a variable. But looked at differently, if the value it's copying is the result, and storing that value into a variable is just a side-effect, then it looks like an operator that does nothing to a value except calculate it (and have a side-effect). If this doesn't sound plausible, consider this example:

a = 2; b = 2; c = 2;
d = ( a + ( b + ( c + 3 ) ) );         // d becomes 9
d = ( a = ( b = ( c = 3 ) ) );         // d ( and a, b and c) becomes 3
d = a = b = c = 3;               // d ( and a, b and c) becomes 3

Line 2 is fairly straightforward, it's just 'd = a + b + c + 3' with more parentheses than are really needed. In Line 3 we can think like this: c is assigned 3, and passes 3 on, so (c = 3 ) is 3, then b is assigned that new 3, and so on. Finally, line 4 shows that the parentheses can be dropped, leaving us with a shorthand way of assigning the same value to numerous variables at once.

As for C and other C-like languages, mixing up = and == is a common source of bugs. See the 'Disappearing Data' chapter.

There are other assignment operators: compound ones. All the bit and arithmetic operators can be combined with = in a way which allows simple expressions to be written in a shorthand way similar to ++ and --. Here is an example for plus. See the Reference Section for the rest.

a += 3;                  // same as a = a + 3;

© 1997 by Wrox Press. All rights reserved.