Skip to study material
← Question index

QUESTION 66 · Operators

Explain simple and compound assignment operators.

5 marks

Answer in brief

Assignment operators store a value in a writable object, such as an ordinary variable. The simple assignment operator is =.

Simple assignment

In total = 20;, the value 20 is stored in total. In total = a + b;, the right-hand expression is calculated first and its result is converted to the type of total for storage. The left side must be a valid destination; 20 = total; is invalid.

Compound assignment

  1. +=: total += 5 adds 5 to total.
  2. -=: total -= 5 subtracts 5.
  3. *=: total *= 5 multiplies by 5.
  4. /=: total /= 5 divides by 5 using the relevant arithmetic types.
  5. %=: total %= 5 stores the integer remainder.
  6. Bitwise forms: &=, |=, ^=, <<= and >>= combine a bit operation with assignment.

Worked example

Starting with int total = 10;, total += 5; gives 15. Next, total *= 2; gives 30. Finally, total -= 4; gives 26. For a simple variable, total += 5 has the usual effect of total = total + 5. A compound assignment evaluates its left operand only once.

Important points

= assigns; == compares. Assignment operators group from right to left: a = b = 0 stores zero in b and then a, when their types permit it. Do not divide by zero. Check whether a conversion loses a fraction or whether arithmetic exceeds the type range. A const-qualified object cannot be assigned a new value through that object.

Reference table

↔ Scroll horizontally on a small screen
Assignment forms
FormSimple-variable explanation
x = yStore the converted value of y in x.
x += yAdd y to x and store the result in x.
x -= ySubtract y from x.
x *= yMultiply x by y.
x /= yDivide x by y, respecting the operand types.
x %= yStore the integer remainder.
x &= maskApply bitwise AND and store the result.
x <<= countShift and store the result, subject to valid shift rules.

Key points

  • = assigns; == compares.
  • The stored result is converted to the destination type.