Why am I getting strange results with simple arithmetic operations?

Tagged:

Or, why is 3 + 5 * 4 = 32?

For some people, this is the least cool feature of Smalltalk. Operators don't have any precedence in Smalltalk and expressions are evaluated left-to-right:

3 + 5 * 4 = (3 + 5) * 4 = 8 * 4 = 32
3 + 4 * 5 = (3 + 4) * 5 = 7 * 5 = 35

In practice, this rarely matters, but it is still something to be aware of.

This is one of the coolest features of Smalltalk. With one stroke the language has stripped away the entire operator concept and substituted message sends for it. Operator-wise precedence rules never did anything for me other than inject bugs at random whenever I extend expressions with new value combinations.

Here is something I did:

$var = funcall()
  ? result1
  : result2;

later changed to:

$var = funcall()
       and other_funcall()
  ? result1
  : result2;

taking a good chunk of time a couple weeks later when I noticed the bug I had introduced.

Perhaps I have shown a little too much pathos in the above, but I loathe precedence rules.

User login