Exercise caution when using the increment/Decrement Operators (C ++) and Decrement Operators
Incrementing ++ and decimal operators-both seemingly and in use, they all feel simple and elegant, but there are uncontrollable traps in them, we must be careful to avoid uncontrollable situations due to incorrect usage.
For example: x = 2 * x ++ * (3-++ x); assume that x = 3. What is the value of x after the expression is calculated?
You can analyze it like this: first 3-++ x gets-1, and then the value of x is 4;
Then 2*4 *-1 = -- 8;At this time, the x value is 5?
Then x =-8
The final value of x is-8?
When you implement this expression in VS2017, you will find that the obtained value is-7. Why is it not-8? After the assignment, the + 1 operation is performed?
Yes. In the implementation of VS2017, the plus one operation of ++ x is performed only after the value is assigned.
In fact, in C ++, there is no rigid rule on when to add x (for example, there is no rule that we previously thought that x ++ will add x after computation)
In C ++, onlySequence pointComplete allSide effectsEvaluation, that is to say, only the operation of adding one before the order point is guaranteed, so there will be different situations in different systems, which is uncontrollable.
Ps:
Side effect: Some things (such as values stored in variables) are modified during expression calculation.
Sequence point: a point in the program execution process. (For example, in C ++, a semicolon is a sequence point, and the end of any complete expression is a sequence point. Other more order points are not stated here)
Complete Expression: it is not a word expression of another larger expression (for example, the expression section in the expression statement has been used as the expression for detecting conditions in the while LOOP)
Therefore, when using the incrementing and decreasing Operators, please be careful to avoid this trap.