Question #50430

Why is the order of evaluation of arithmetic expressions important? Illustrate your answer with an example showing the effect parentheses can have on the way an expression is evaluated.

Expert's answer

Answer:
Arithmetic operations in Visual Basic executes accordingto the common arithmetic rules:
1) Compiler evaluates expression fromleft to right
2) Multiplication and division havebigger priority then addition and substraction
3) Parentheses change evaluation order

Examples:
result =3 + 2 * 2 ' resultis 7
result =(3 + 2) * 2 ' resultis 10
result =3 + 2 * 4 / 2 ' resultis 7, first 2* 4, then 8 / 2, then 3 + 4
result =3 + 2 * 4 / 2 * 2 'result is 11, first -> 2* 4, then 8 / 2, then 4 * 2, then 3 + 8
result = 3 + 2 * 4 / (2 * 2) ' result is 5, first -> 2* 2, then 2 * 4, then 8 / 4, then 3+2

Dim a, b, c, d, e, f, g As Double
a = 8.0
b = 3.0
c = 4.0
d = 2.0
e = 1.0
f = (a - b) + ((c / d) * e) = (8 - 3) + ((4 / 2) * 1) = 7
Parentheses priority still from left to right andcannot be changed.

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS