5.8. Compound Assignment OperatorsVisual Basic provides several compound assignment operators for abbreviating assignment statements. For example, the statement value = value + 3 can be abbreviated with the addition assignment operator, += as value += 3 The += operator adds the value of the right operand to the value of the left operand and stores the result in the left operand's variable. Any statement of the form variable = variable operator expression can be written in the form variable operator= expression where operator is one of the binary operators +, -, *, ^, &,/ or \, and variable is an lvalue ("left value"). An lvalue is a variable or property that can appear on the left side of an assignment statement. We will learn how to declare constants in Section 7.16constants cannot be lvalues. Figure 5.8 includes the compound assignment operators, sample expressions using these operators and explanations.
The =, +=, -=, *=, /=, \=, ^= and &= operators are always applied last in an expression. When an assignment statement is evaluated, the expression to the right of the operator is always evaluated first, then the value is assigned to the lvalue on the left. Figure 5.9 calculates a power of two using the exponentiation assignment operator. Lines 12 and 16 have the same effect on the variable result. Both statements raise result to the value of variable exponent. Note that the results of these two calculations are identical. Figure 5.9. Exponentiation using a compound assignment operator.
|