Skip to content

Commit

Permalink
Attempts to make corrections about Exercise 4.31
Browse files Browse the repository at this point in the history
There is no different between prefix and postfix in this example. ➗
  • Loading branch information
pezy committed Sep 29, 2014
1 parent 2fc3ddb commit 489dd93
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion ch04/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,26 @@ reference: [sizeof operator](http://en.cppreference.com/w/cpp/language/sizeof)
##Exercise 4.31
>The program in this section used the prefix increment and decrement operators. Explain why we used prefix and not postfix. What changes would have to be made to use the postfix versions? Rewrite the program using postfix operators.
postfix will copy itself as return, then increment or decrement. prefix will increment or decrement first, and return itself. so prefix is more effective in this program.(reduce one copy space.)
~~postfix will copy itself as return, then increment or decrement. prefix will increment or decrement first, and return itself. so prefix is more effective in this program.(reduce one copy space.)~~

We use prefix and not postfix, just because of the `Advice: Use Postfix Operators only When Necessary` on `§4.5. Increment and Decrement Operators`.

>**Advice: Use Postfix Operators only When Necessary**
>Readers from a C background might be surprised that we use the prefix increment in the programs we've written. The reason is simple: The prefix version avoids unnecessary work. It increments the value and returns the incremented version.The postfix operator must store the original value so that it can return the unincremented value as its result. If we don’t need the unincremented value, there’s no need for the extra work done by the postfix operator.
>For ints and pointers, the compiler can optimize away this extra work. For more complicated iterator types, this extra work potentially might be more costly. By habitually using the prefix versions, we do not have to worry about whether the performance difference matters. Moreover—and perhaps more importantly—we can express the intent of our programs more directly.
So, it's just a good habits. And there are no changes if we have to be made to use the postfix versions. Rewrite:
```cpp
for(vector<int>::size_type ix = 0; ix != ivec.size(); ix++, cnt--)
ivec[ix] = cnt;
```

This is not an appropriate example to discuss the difference of prefix and postfix. Look at the section `Built-in comma operator` on [this page](http://en.cppreference.com/w/cpp/language/operator_other).

-----
reference: [Usage of the Built-in Comma Operator](http://stackoverflow.com/questions/22591387/usage-of-the-built-in-comma-operator)

##Exercise 4.32
>Explain the following loop.
Expand Down

0 comments on commit 489dd93

Please sign in to comment.