Originale-mail to me for new edition

 

Operator precedence rules

 

In complex expressions, rules of precedence determine the order in which operations are performed.

 

Operators

Precedence

@, not

first (highest)

*, /, div, mod, and, shl, shr, as

second

+, -, or, xor

third

=, <>, <, >, <=, >=, in, is

fourth (lowest)

 

An operator with higher precedence is evaluated before an operator with lower precedence, while operators of equal precedence associate to the left. Hence the expression

X + Y * Z

multiplies Y times Z, then adds X to the result; * is performed first, because is has a higher precedence than +. But

X - Y + Z

first subtracts Y from X, then adds Z to the result; - and + have the same precedence, so the operation on the left is performed first.

You can use parentheses to override these precedence rules. An expression within parentheses is evaluated first, then treated as a single operand. For example,

(X + Y) * Z

multiplies Z times the sum of X and Y.

Parentheses are sometimes needed in situations where, at first glance, they seem not to be. For example, consider the expression

X = Y or X = Z

The intended interpretation of this is obviously

(X = Y) or (X = Z)

Without parentheses, however, the compiler follows operator precedence rules and reads it as

(X = (Y or X)) = Z

which results in a compilation error unless Z is Boolean.

Parentheses often make code easier to write and to read, even when they are, strictly speaking, superfluous. Thus the first example above could be written as

X + (Y * Z)

Here the parentheses are unnecessary (to the compiler), but they spare both programmer and reader from having to think about operator precedence.

 

Topic groups

 

See also

About operators

 

 

译文

 

运算符优先规则

 

在复合表达式中,优先级规则决定了运算被执行的顺序。

 

运算符

优先级

@, not

第一(最高)

*, /, div, mod, and, shl, shr, as

第二

+, -, or, xor

第三

=, <>, <, >, <=, >=, in, is

第四(最低)

 

优先级高的运算符在优先级低的运算符之前求值,优先级相同时自左向右求值。因此,表达式

X + Y * Z

先运算Y乘以Z,然后将乘积(运算结果)与X相加;运算符 * 先被执行,因为它比运算符 + 具有更高的优先级。而表达式

X - Y + Z

首先从X中减去Y,然后再对结果加上Z;运算符 - + 具有相同的优先级,因此自左向右求值。

可以使用圆括号超越所有的优先级规则。圆括号中的表达式最先被求值,因此可以被视为一个单独的操作数。例如,表达式

(X + Y) * Z

将用XY的和去乘以Z

有时候圆括号是需要的,尽管乍一看似乎不需要。例如,对于表达式

X = Y or X = Z

要实现预期的解释,应清楚地加上圆括号,写成

(X = Y) or (X = Z)

然而,如果没有圆括号,编译器将根据优先级规则将表达式解释为

(X = (Y or X)) = Z

这样将导致编译错误,除非Z是一个布尔型。

圆括号通常使代码更容易读写,尽管有时严格来说是多余的。因此,上面第一个范例可以写成

X + (Y * Z)

虽然这里的圆括号对编译器来说是不必要的,但它们使得程序员和读者都用不着考虑运算符的优先级。

 

主题组

 

相关主题

运算符