I l@ve RuBoard |
![]() ![]() |
5.13 Side EffectsUnfortunately, C++ allows you to use side effects. A side effect is an operation that is performed in addition to the main operation executed by the statement. For example, the following is legal C++ code: size = 5; result = ++size; The first statement assigns size the value of 5. The second statement:
But in what order? There are three possible answers:
The correct answer is 2: The increment occurs before the assignment. However, 3 is a much better answer. The main effects of C++ are confusing enough without having to worry about side effects.
C++ actually provides two forms of the ++ operator. One is variable++ and the other is ++variable. The first: number = 5; result = number++; evaluates the expression and then increments the number, so result is 5. The second: number = 5; result = ++number; increments first and then evaluates the expression. In this case result is 6. However, using ++ or -- in this way can lead to some surprising code: o = --o - o--; The problem with this is that it looks like someone is writing Morse code. The programmer doesn't read this statement; she decodes it. If you never use ++ or -- as part of any other statement, but always put them on a line by themselves, the difference between the two forms of these operators is not noticeable.
More complex side effects can confuse even the C++ compiler. Consider the following code fragment: value = 1; result = (value++ * 5) + (value++ * 3); This expression tells C++ to perform the following steps:
Steps 1 and 2 are of equal priority, unlike the previous example, so the compiler can execute them in any order it wants to. It may decide to execute step 1 first, as shown in Figure 5-2, but it may execute step 2 first, as shown in Figure 5-3. Figure 5-2. Expression evaluation, method 1![]() Figure 5-3. Expression evaluation, method 2![]() Using the first method, we get a result of 11; using the second method, the result is 13. The result of this expression is ambiguous. By using the operator ++ in the middle of a larger expression, we created a problem. (This is not the only problem that ++ and -- can cause. We will get into more trouble in Chapter 10.) To avoid trouble and keep programs simple, always put ++ and -- on a line by themselves. ![]() |
I l@ve RuBoard |
![]() ![]() |