Side effects
A side effect is a result of an operator, expression, statement, or function that persists even after the operator, expression, statement, or function has finished being evaluated.
Side effects can be useful:
1 | x = 5; |
The assignment operator has the side effect of changing the value of x permanently. Even after the statement has finished executing, x will have the value 5.
Side effects can also be dangerous:
1 | int x = 5; |
2 | int nValue = Add(x, ++x); |
C++ does not define the order in which function parameters are evaluated. If the left parameter is evaluated first, this becomes a call to Add(5, 6), which equals 11. If the right parameter is evaluated first, this becomes a call to Add(6, 6), which equals 12!
As a general rule, it is a good idea to avoid the use operators that cause side effects inside of compound expressions. This includes all assignment operators, plus the increment and decrement operators. Any operator that causes a side effect should be placed in it’s own statement.
Note that side effects are not confined to operators, expressions, and statements. Functions can also have side effects, which we will discuss in the section on global variables (and why they are evil).