Consider the following statement in C
j=2 * 3 / 4 2.0 / 5 8 / 5;
If the parenthesis is done considering BODMAS rule:
j=(2 * (3 / 4)) (2.0 / 5) (8 / 5); // then j = 0
If we take the priority of operators in C
j=((2 * 3) / 4) (2.0 / 5) (8 / 5); // then j = 2
Which one is the correct order?
CodePudding user response:
You're misunderstanding BODMAS (or for Americans like me, PEMDAS). It's not a strict one at a time, in order application. Parenthesized, it groups as (B)(O)(DM)(AS). Division and multiplication are the same precedence (in both grade school arithmetic and the C operator precedence); similarly, addition and subtraction are the same precedence. You'll note the American acronym even flips the D and the M; it doesn't matter, because they're the same precedence, but trying to render a word with the M and D in the same space would be ugly, so we just fudge it.
Both the grade school and C approach work from left to right when the operators are equal precedence, so the correct evaluation order is:
j=((2 * 3) / 4) (2.0 / 5) (8 / 5);