Next: Formatting of output
Up: Further Assignment Statements &
Previous: Increment and Decrement Operators
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:
variablethe 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.=
variable op(
expression)
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; |
%=
the two
operands may be any arithmetic type. The compound modulus operator
requires that both operands are integer types.