next up previous
Next: Formatting of output Up: Further Assignment Statements & Previous: Increment and Decrement Operators

Specialised Assignment Statements

Another common situation that occurs is assignments such as the follows:

sum = sum + x;
in which a variable is increased by some amount and the result assigned back to the original variable. This type of assignment can be represented in C++ by:
sum += x;

This notation can be used with the arithmetic operators +, -, *, / and %. The general form of such compound assignment operators is:

variable op= expression
which is interpreted as being equivalent to:
variable = variable op ( expression )
the expression is shown in brackets to indicate that the expression is evaluated first before applying the operator op. The following example illustrate the use of compound assignment operators.
total += value; or total = total + value;
prod *= 10; or prod = prod * 10;
x /= y + 1; or x = x/(y + 1);
n %= 2; or n = n % 2;
Except for the case of the compound modulus operator %= the two operands may be any arithmetic type. The compound modulus operator requires that both operands are integer types.


next up previous
Next: Formatting of output Up: Further Assignment Statements & Previous: Increment and Decrement Operators
Peter JB King
1999-08-31