ADVICE: MANAGING COMPOUND EXPRESSIONS
Beginning C and C++(www.cppentry.com) programmers often have difficulties understanding order of eva luation and the rules of precedence and associativity. Misunderstanding how expressions and operands are eva luated is a rich source of bugs. Moreover, the resulting bugs are difficult to find because reading the program does not reveal the error unless the programmer already understands the rules.
Two rules of thumb can be helpful:
1. When in doubt, parenthesize expressions to force the grouping that the logic of your program requires.
2. If you change the value of an operand, don’t use that operand elsewhere in the same statement. If you need to use the changed value, then break the expression up into separate statements in which the operand is changed in one statement and then used in a subsequent statement.
An important exception to the second rule is that subexpressions that use the result of the subexpression that changes the operand are safe. For example, in *++iter the increment changes the value of iter, and the (changed) value of iter is then used as the operand to *. In this, and similar, expressions, order of eva luation of the operand isn’t an issue. To eva luate the larger expression, the subexpression that changes the operand must first be eva luated. Such usage poses no problems and is quite common.
按照C++(www.cppentry.com) 标准,一个对象的值在一个表达式里只能改变一次, 因此i= i++是未定义行为(undefined)。此外,如果一个表达式修改了某个对象的值,那么这个对象在该表达式里只能出现一次(即上面的第2 点建议), 因为副作用发生的时机是未指明的(unspecified)。
Do not use an increment or decrement operator on the same object in more than two subexpressions of the same expression.
One safe and machine-independent way to rewrite the previous comparison of two array elements is
- if (ia[index] < ia[index + 1]) {
-
Now neither operand can affect the value of the other.