Visual Basic 2005 for Programmers (2nd Edition)

5.8. Compound Assignment Operators

Visual 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.

Figure 5.8. Compound assignments operators

Compound assignment operator

Sample expression

Explanation

Assigns

Assume: c = 4, d = "He"

+=

c += 7

c = c + 7

11 to c

-=

c -= 3

c = c - 3

1 to c

*=

c *= 4

c = c * 4

16 to c

/=

c /= 2

c = c / 2

2 to c

\=

c \= 3

c = c \ 3

1 to c

^=

c ^= 2

c = c ^ 2

16 to c

&=

d &= "llo"

d= d & "llo"

"Hello" to d

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.

1 ' Fig. 5.9: Assignment.vb 2 ' Using a compound assignment operator to calculate a power of 2. 3 Module Assignment 4 Sub Main() 5 Dim exponent As Integer ' power input by user 6 Dim result As Integer = 2 ' number to raise to a power 7 8 ' prompt user for exponent 9 Console.Write("Enter an integer exponent: ") 10 exponent = Console.ReadLine() ' input exponent 11 12 result ^= exponent ' same as result = result ^ exponent 13 Console.WriteLine("result ^= exponent: " & result) 14 15 result = 2 ' reset result to 2 16 result = result ^ exponent ' same as result ^= exponent 17 Console.WriteLine("result = result ^ exponent: " & result) 18 End Sub ' Main 19 End Module ' Assignment

Enter an integer exponent: 8 result ^= exponent: 256 result = result ^ exponent: 256

Категории