tags:

views:

137

answers:

4

When a expression is evaluated in C/C++, does it follow BODMAS [Bracket open Division Multiply Addition Substraction] rule? If not then how they are evaluated?

EDIT: More clearly, If the following expression is evaluated according to BODMAS rule,

(5 + 3)/8*9

First what is in brackets is processed.

8/8*9.

Then Division is done.

1*9

And then multiplication and so on.

+5  A: 

There are far more operators than that. You can find a precedence tables for C++ and C.

But yes, you'll find it respects that. (Though I'm not sure it's exactly what you've said...)

GMan
That's how they're _parsed_. Evaluation is not guaranteed to happen in that order.
MSalters
@MSalters: Sub-expressions have unspecified evaluation order, yes.
GMan
+4  A: 

There are two answers to this question.

One is that C++ does follow standard mathematical precedence rules, which you refer to as BODMAS. You can see the order in which C++ associates all its operators here.

However, if any of the expressions involved in the operation have side effects, then C++ is not guaranteed to evaluate them in what one might consider to be standard mathematical order. That's sort of an advanced topic, however.

John Calsbeek
+1 for mentionning weird consequences of side effects.
mouviciel
+2  A: 

Other people have given you links to operator precedence lists. These are well and good. However, if you need to look at an operator precedence table to determine what your code tells computers to do, please take pity on your code's maintainers (including future you) and just use parentheses. It makes your intention much clearer and saves time and heartache in the long run.

Nathon
A good rule to follow. My code always has more parentheses than necessary, but my code always works.
Mark Ransom
I on the other hand think that many adjacent parentheses make code *much* harder to read and thus I always strive to reduce the number of parentheses if readability doesn’t suffer (which is apparently a subjective measure).
Konrad Rudolph
Nathon
I deliberately don't memorize the precedence table. That way, if it's likely to be unclear to somebody else, then it's likely to be unclear to me and I'll instinctively put parentheses around it.
David Thornley