问题描述
为什么不简单地评估从左到右?有人可以解释一下优先级如何使代码更具可读性吗?对我来说,这似乎需要更多的思考和更多的出错可能性.爱因斯坦说:一切都应该尽可能简单,但不要简单."我猜他不是程序员.
Why not simply evaluate Left to Right? Can someone explain how precedence makes code more readable? To me it seems to require more thought and more possibility for error. Einstein said, "Everything should be made as simple as possible, but no simpler." I guess he wasn't a programmer.
推荐答案
因为在数学上,在发明任何计算机语言之前,都存在运算符优先级,例如
because in Mathematics, before the invention of any computer language, there was operator precedence, e.g.
2 + 5 * 3 = 17 (and not 21)
*
运算符的优先级没有比+
运算符高的语言会引起混淆.
A language not having a higher precedence for the *
operator than for the +
operator would generate confusion.
C ++的另一个示例:
Another example from C++:
std::cout << 7 * 8 << std::endl;
如果*
运算符没有优先于<<
运算符,则不会编译:
If the *
operator did not have precedence over the <<
operator, this would not compile:
- 首先会评估
-
std::cout << 7
,结果是std::cout
(副作用是会打印7
) - 然后人们想对
std::cout * 8
求值,除非有人定义一个真正怪异的运算符*
来将outputstream
乘以整数,否则该值未定义.
std::cout << 7
would be evaluated first, yieldingstd::cout
as a result (with the side effect that7
would be printed)- then one would want to evaluate
std::cout * 8
which -- unless somebody defines a really weird operator*
for multiplying anoutputstream
by an integer -- is not defined.
运算符优先级无需在常识"中加上不必要的括号(尽管我同意,在某些情况下,由于人们不了解实际优先级,所以会引入错误)
Operator precedence allows not having to put unnecessary parentheses 'within common sense' (although I agree that in some cases people introduce bugs because they are not aware of the actual precedences)
现在您可能会问:为什么数学具有运算符优先级? 此Wikipedia文章提到了一些历史事实,并链接到一个讨论论坛.对我而言,重要的论据是编写多项式时的论据,例如
Now you might ask: why does Mathematics have operator precedence ? This wikipedia article mentions some historical facts and links to a discussion forum. For me, an imporant argument is the one that when writing polynomials, e.g.
ax^2 + bx + c
没有运算符优先级,则必须将它们写为:
without operator precedence, one would have to write them as:
(a(x^2)) + (bx) + c
这篇关于为什么语言具有运算符优先级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!