副作用Side Effects

表达式的计算顺序由特定实现定义,但语言保证特定的计算顺序时除外(如计算的优先级和顺序中概述)。The order of evaluation of expressions is defined by the specific implementation, except when the language guarantees a particular order of evaluation (as outlined in Precedence and Order of Evaluation). 例如,下列函数调用中将出现副作用:For example, side effects occur in the following function calls:

add( i + 1, i = j + 2 );  
myproc( getc(), getc() );  

函数调用的参数可按任意顺序进行计算。The arguments of a function call can be evaluated in any order. 表达式 i + 1 可以在 i = j + 2 前计算,或者 i = j + 2 可以在 i + 1 前计算。The expression i + 1 may be evaluated before i = j + 2, or i = j + 2 may be evaluated before i + 1. 每种情况下的结果都不同。The result is different in each case. 同样,无法保证将哪些字符会实际传递到 myprocLikewise, it is not possible to guarantee what characters are actually passed to the myproc. 由于一元递增和递减运算涉及赋值,因此此类运算可能导致副作用,如以下示例中所示:Since unary increment and decrement operations involve assignments, such operations can cause side effects, as shown in the following example:

x[i] = i++;  

在此示例中,修改后的 x 值不可预知。In this example, the value of x that is modified is unpredictable. 下标的值可以是 i 的新值或旧值。The value of the subscript could be either the new or the old value of i. 结果因编译器或优化级别而异。The result can vary under different compilers or different optimization levels.

由于 C 未定义副作用的计算顺序,因此上面讨论的两种计算方式都是正确的,并且其中一个是可以实现的。Since C does not define the order of evaluation of side effects, both evaluation methods discussed above are correct and either may be implemented. 若要确保你的代码可移植且清晰明了,请避免使用依赖于副作用的特定计算顺序的语句。To make sure that your code is portable and clear, avoid statements that depend on a particular order of evaluation for side effects.

另请参阅See Also

表达式计算Expression Evaluation