BODMAS - the order a computer evaluates arithmetic expressions
Archive - Originally posted on "The Horse's Mouth" - 2012-11-09 13:46:09 - Graham Ellis
What order does a computer program use to evaluate expressions? If I write 2 + 3 * 4 + 5
does it start off, left to right ... 2 + 3 is 5
5 * 4 is 20
20 + 5 is 25 No! it does not, even though the newcomer might think that was the most natural way for it to work.
Almost all programming languages use a system in which operators of some types are run first, then operators of different types. In our example above, it runs he multiplication before the additions, so 3 * 4 is 12
2 + 12 is 14
14 + 4 is 19
And you see that's a very different result to the 25 if we had gone left to right. This really matters to all programmers!
There's a common acronymn that's used - BODMAS:
Brackets . Order / Index Division Multipication Addition Subtraction
• Anything that's in round brackets is run first (and that's very important, because it means you can add brackets to change the order of evaluation if you need to do so)
• Then orders / indexes are run. They are "raise to the power of" operations such as 2 ** 7
for 2 to the power 8 - i.e. 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 which is 256
• Then divisions and multiplications (these are done at the same time, from left to right within your expression) 16 / 4 * 2
will give the result 8 rather than 2, because the division, which is the same level as the multiplication, is to the left of the multiplication.
• Finally (in BODMAS), additions and subtractions are performed in the same "pass", again from left to right.
Precedence order may confuse the newcomer from time to time, but the heirarcy tree that's used has stood the text of time, and is sensible for real use, and pretty standard. There are many other operators you'll find yourself using in some of the languages we teach, and they typically slot in "naturally".