Precendence of Operators


© Swapna Kamat

Precendence of Operators

Order of Precedence in Statements

Consider the following statement:

x = 9 + 4 * 2


Depending on how you look at it, x could have two values--26 or 17. If you do the addition of 9 + 4 first and then multiply by 2, you get 26. However, if you multiply 4 * 2 first and then add 9, you get 17. The answer you get depends on the order in which things happen. This order is referred to as order of precedence or hierarchy of operators

In Visual Basic, the default order of precedence is that in a statement with multiplication/division operators and addition/subtraction operators, multiplication/division is performed first, before the addition/subtraction. In the preceding example, the default answer is 17. Other operators, such as comparison, logical, and string, are also affected by precedence.

When multiple types of operators are in a single statement, operator precedence controls what's performed first. Math operators are performed first, then comparison operators, and finally logical operators

Operation Operator Symbol
Exponentiation ^
Negation (unary) -
Multiplication, division *, /
Integer division \
Modulus mod
Addition, subtraction +, -
Concatenation (string) &
Comparison operators =, <>, <, >, <=, >+
Logical operators Not, And, Or, Xor, Eqv, Imp, Like, Is

Parentheses are used to control specifically which parts of a statement are performed first. Without parentheses, operator precedence allows the program to determine what operation to do first. To ensure that arithmetic operations happen in the order you want them to, you can use parentheses to group operations. For example, by using the preceding statement, you could group operations as

x = (9 + 4) * 2 `results in 26
or
x = 9 + (4 * 2) `results in 17
In the next article, we shall study about strings and their implementations in VB

Go To Page: 1


The copyright of the article Precendence of Operators in Learning Visual Basic is owned by . Permission to republish Precendence of Operators in print or online must be granted by the author in writing.

Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo