Subtraction - Order of Evaluation
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 - 开发者_C百科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
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
.
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.
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
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.
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.
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.
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.
精彩评论