The following table shows some of the Visual Basic arithmetic operators and
specifies their precedence. (Precedence tells us that to correctly
evaluate the expression 3 + 4 * 2 you must first multiply 4 by 2 and then
add the intermediate result to 3 to yield a final
result of 11. (This should be contrasted
to the value 14 which you would get if you add 3 and 4 before multiplying
by 2.) The highest precedence operators (first to be performed) are
at the top of the table. As you move down the table, the precedence
of the operators decreases. Where two or more operators share the
same precedence, they will always be evaluated from left to right.
Thus, 12 / 6 / 2 yields the result 1 because you first divide 12 by 6 to
obtain the intermediate result 2. This value is then divided by 2 to produce
the number 1. If you had first divided 6 by 2, you would get 3.
Then, dividing 12 by 3 would give you a value of 4. Remember, when
several operators have the same precedence, they are evaluated from left
to right. If you want an expression to be evaluated in an order that
is different from that specified in the following table, you can always
use parentheses to specify this. For example, 4 + 2 * 3 - 6 evaluates
to 4. While, (4 + 2) * 3 - 6 evaluates to 12. And, (4 + 2) *
(3 - 6) evaluates to -18. The precedence of arithmetic operators matters.
If you do not get it correct, you will get the wrong answers.
|
|
Meaning |
|
|
Exponentiation -- raise to a power. For example, 2 ^ 3 equals 8. |
|
|
Negation -- the following operand is to be multiplied by minus 1. (i.e., interpreted as a negative value.) |
|
|
Multiplication Division. |
|
|
Integer division -- truncation. 7 \ 3 equals 2. 8 \ 3 also equals 2. Any fractional portion in the result is discarded. |
|
|
Modulus -- remainder. Defined for integers, Mod returns the remainder. For example, 17 Mod 9 equals 8. |
|
|
Addition Subtraction. |
|
|
Concatenation. Strictly speaking, this is a string operator. However, it can be used in an arithmetic expression. For example, 3 & 19 will return 319, while (3 & 19) + 4 will return 323. Bear in mind that VB is a very forgiving language. It will make every effort to convert a value to the approriate type to allow the program to continue. Most programming languages will crash with a compile or execution error if you attempt to combine string concatenation with arithmetic operators. |
All programming languages have precedence rules regarding the order in which arithmetic operators are performed. You need to be aware of these rules in whatever language you are using.
Here's a test, what is value of the arithmertic expression: