본문 바로가기

Application-level프로그래밍

Side effect

수식의 계산에서 계산 순서에 따라 결과가 달라질 수 있는 경우라고 정리하면 될까?
Side effect 가 일어날 때에는 좀더 명확하게 수식을 고치는 것을 권장하는 것이 결론.  

출처: MSDN
(ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_vclang/html/d9b3004a-830e-43a0-bea5-8989d501d670.htm)

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. 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. Likewise, 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++;

In this example, the value of x that is modified is unpredictable. 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.

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