The information in this article applies to:
SUMMARY
Side effect operators (++, --, =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, and
>>=) may cause unexpected results if they are used on the same variable or
memory location more than once in the same expression. The order in which
side effects occur within an expression is not specified.
MORE INFORMATIONIt is easy to accidentally write nonportable code with the C language. Below are some other common examples of statements that can cause side effects during run time:
The above statement can produce different results with different compilers,
depending on whether "n" is incremented before "power" is called. The
correct code is as follows:
Another common pitfall is the following:
The question is whether the subscript of "a" is the old value of "i" or the
new value. The correct code is as follows:
Another example is as follows:
The compiler is allowed to "p" twice at the end after doing the two
assignments, if it so chooses. To ensure correct code generation, you must
code as follows:
In general, any object may have its stored value modified at most once in a
single expression; in addition, the prior value shall be accessed only to
determine the value to be stored. Therefore,
is allowed because "i" is modified only once, and "i" is accessed only to
determine what to store in "i", but
is undefined because "i" is modified more than once in the course of the
evaluation of the expression.
Instead, the following pair of statements is correct:
The statement:
is undefined, because, although "i" is only modified once, it is accessed
both to determine the value to be stored in "i" by the ++ operator and as a
subscript.
Additional query words:
Keywords : kbLangC kbVC100 kbVC150 kbVC200 kbVC400 kbVC500 kbVC600 |
Last Reviewed: July 1, 1999 © 2000 Microsoft Corporation. All rights reserved. Terms of Use. |