Navigation:  Tutorials > Beginners Guide to Smalltalk > Objects and Messages >

Order of Messages

Previous pageReturn to chapter overviewNext page

The order in which Smalltalk evaluates more complicated arithmetic expressions is different than you might expect, especially if you're used to other computer languages. For example, try displaying the result of:

3 + 4 * 5


You might expect to see a result of 23 but Smalltalk reports 35. This is because we normally think of multiplication and division operators having a higher precedence than addition or subtraction operators. We would expect the higher precedence multiplication to be performed before the lower precedence addition. This is not the case, however. In Smalltalk, all binary messages are taken to have the same precedence and will be evaluated in "first come, first served" order. This is a minor inconvenience but can be remedied by always using appropriate parentheses whenever there might be confusion. See that the following now yields the expected result:

3 + (4 * 5)


Smalltalk does enforce some precedence rules, though. They are very straightforward and, in most cases (apart from the above quirk concerning arithmetic precedence) they yield code that is eminently readable. The order of message evaluations in any expression is as follows:

Simple Messages (highest precedence)
Binary Messages
Keyword Messages (lowest precedence)

Try the following examples and try to predict the results:

3 squared + 4 squared

#(130 140 150 160) at: 4 - 2

5 factorial gcd: 'a string' size "gcd: computes Greatest Common Divisor"

3 squared + 4 squared sqrt

(3 squared + 4 squared) sqrt