3 Public Class PowerOf2Ĥ ' calculates 2 raised to the exponent entered by the user.
4.9: PowerOf2.vb 2 ' Calculates 2 raised to the exponent entered by the user. Exponentiation using a compound assignment operator. The results of these two calculations are identical as shown in the sample output. Lines 12 and 17 each raise variable result to the value of variable exponent. In this case, we initialize variable exponent to the value of exponentTextBox's Text property. In line 8, we take advantage of a Visual Basic feature that allows variable initialization to be incorporated into a declaration. Demonstrating the ^= Compound Assignment Operatorįigure 4.9 calculates a power of 2 using the exponentiation assignment operator. When a compound assignment is evaluated, the appropriate operator is applied to the lvalue's original value and the value to the operator's right, then the resulting value is assigned to the lvalue on the left. When an assignment ( =) 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. The =, +=, -=, *=, /=, \=, ^= and &= operators are always applied last in an expression.
We'll learn how to declare constants in Section 6.10-constants cannot be lvalues. The variable on the left side of an assignment operator must be an lvalue ("left value")-a modifiable variable or property that can appear on the left side of an assignment statement. Figure 4.8 summarizes the compound assignment operators. 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.
Which mentions the variable value on both sides of the assignment, can be abbreviated with the addition assignment operator, += as value += 3 For example, the statement value = value + 3 The compound assignment operators enable you to abbreviate assignment statements. Learn More Buy 4.9 Compound Assignment Operators Visual Basic 2010 How to Program, 5th Edition