TechnologyUK - Programming (VB6) Logo

Maths Operators

Math operators allow you to calculate the result of an arithmetic expression and assign it to a variable. The table below describes Visual Basic's main math operators.

Visual Basic Math Operators
OperatorExampleDescription
+ Price = Nett + Discount Adds two values together
- Nett = Price - 4.00 Subtracts the second value from the first value
* Total = Price * Qty Multiplies two values together
/ Allocation = Tickets / Members Divides the first value by the second value
^ Result = Myval ^ 3 Raises the first value to the power given by the second value

Note that all variables used in an expression must be declared and initialised before they can be used. The value of the expression that follows the equals symbol (=) is assigned to the variable that precedes the equals symbol.

Operator precedence

In a complex expression involving a number of operators, Visual Basic carries out all of the calculations before assigning the result. Consider the following program statement:

Result = 8 * 10 - 3 + 12 * 20

Combining expressions in this way can produce unexpected results, because Visual Basic carries out the various arithmetical operations in a predetermined order. Visual Basic always calculates exponents first, followed by multiplication and division (working from left to right), then addition and subtration. The result of the above expression (i.e. the value of Result) is therefore 317. Visual Basic first computes the value of 8 * 10, then the value of 12 * 20. VB then subtracts 3 from 80 (8 *10) and adds the result of this calculation to 240 (12*20). Intermediate results are always calculated from left to right. The order of computation is usually referred to operator precedence. It is possible to override operator precedence using parentheses. Visual Basic always computes values inside parentheses before anything else in an expression. The following statement, for example, stores a value of 296 in Result, because the parentheses force VB to compute the subtraction first:

Result = 8 * (10 - 3) + 12 * 20