views:

110

answers:

7

Is it standard across all languages for the following to yield the value 3?

Print(6 - 2 - 1)

In other words, are there any languages that will evaluate " 2 - 1 " before " 6 - 2 "?

I'd like to make this assumption so that I can quit instinctively inserting parentheses ((6 - 2) - 1). It leave me at risk of LISP nightmares.

Thanks

+1  A: 

What you want is left-to-right associativity (as opposed to right-to-left associativity).

It's not guaranteed but most languages are left-to-right associative with arithmetic.

Aaron
+1  A: 

As far as I know, subtraction is always made left-associative (for the obvious reason -- it does what you expect). There may be languages expressly designed not to, but it's a safe assumption that arithmetic almost always works the way you expect.

Dave
+2  A: 

Every language that I know of will evaluate that in the expected order, from left to right. However, I'd suggest you just do a quick test in whatever language you're working in to verify this.

Bill the Lizard
+4  A: 

Generally when multiple operations have the same precedence they are evaluated from left to right similar to arithmetic. I wouldn't want to say ALL languages because I haven't done a survey of all but it makes sense that it should be so. I would still read the docs carefully for whatever new language I was going to try.

Vincent Ramdhanie
This is true for some operations, but not for others. E.g. assignment operators in C-like languages are evaluated from right to left: `x = y = 3` is parsed as `x = (y = 3)`, not `(x = y) = 3`. If there is an exponentiation operator in the language, it will usually be right to left as well.
Alexey Romanov
+5  A: 

In Smalltalk, there is no mathematical precedence.

Mathematical operator are just method mames and thus precedence is treated as for any other method name. Your example will evaluate as expected, but for example 1 + 2 * 3 yields 9 rather than 7.

Adrian
+3  A: 

Just for the sake of mentioning a counter-example, if memory serves APL is strictly right-associative so 6-2-1 would evaluate to 5. I expect someone with an installation of APL or one of its decendants will put us right if I am wrong.

Regards

High Performance Mark
+1  A: 

Stop worrying and trust the operator precedence. Very few languages have precedences that are different than standard math operators. The place to use parentheses is when it is not obvious what the precedence rules are. With standard math operators, it is obvious.

The only language family I know of that has precedence but that doesn't follow standard math rules is the APL family, and in particular the K language. This family has lots of mathematical and invented operators, and they are strictly evaluated right-to-left. But unless you have to deal with those types of languages, don't worry.

Nathan Whitehead