C++ Primer 4/e 在算式这里还有一个忠告:‘Beginning C and C++ programmers often have difficulties understanding order of evaluation and the rules of precedence and associativity. Misunderstanding how expressions and operands are evaluated 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:
-
When in doubt, parenthesize expressions to force the grouping that the logic of your program requires.
-
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 evaluation of the operand isn’t an issue. To evaluate the larger expression, the subexpression that changes the operand must first be evaluated. Such usage poses no problems and is quite common.’
中文版的是这样说:‘C和C++新手常常很难了解“核定次序”以及优先序和结合律的规则。“误解算式和运算元的核定方式”是臭虫的丰富根源。更有甚者,其所导致的臭虫很难被发现,因为除非程式员了解那些规则,否则阅读程式码无法找出错误。
两个经验法则可能会有帮助:
1.如果不甚肯定,请为算式加入小括号,强迫其运算元结合方式符合你的程式所需要的逻辑。
2.如果改变了运算元值,不要在相同述句内的任何其他地方使用同一个运算元。如果需要使用改变后的值,请把算式拆成分离述句,让运算元在某个述句内被改变,再于后续述句内被使用。
第二规则有一个重要例外:任何子算式如果使用“改变运算元值”之子算式的运算结果,都是安全的。例如在*++iter中,递增动作改变了iter的值,而iter改变后的值接着被当作*的运算元。在此算式及类似算式中,运算元核定次序不是问题。当核定较大算式时,算式内“改变运算元值”的子算式一定会先被球值。这个用法没问题,而且满常见的。’
恩,一个亲身的经验就是人要谦卑,不要自以为是的以为自己C和C++很行就拼命用简洁语法,然后下错了运算式还拼命地认为不可能是那里错,到头来侦错的时间会加长许多,在工厂常会被要求针对有可能做错的事作查检表,这里的运算子优先序表及忠告可以列入写C的查检表,应该也不错。
1 則留言
Comments are closed.