section 2.8: Increment and Decrement Operators
The distinction between the prefix and postfix forms of ++ and -- will probably seem strained at first, but it will make more sense once we begin using these operators in more realistic situations.The authors point out that an expression like (i+j)++ is illegal, and it's worth thinking for a moment about why. The ++ operator doesn't just mean ``add one''; it means ``add one to a variable'' or ``make a variable's value one more than it was before.'' But (i+j) is not a variable, it's an expression; so there's no place for ++ to store the incremented result. If you were bound and determined to use ++ here, you'd have to introduce another variable:
int k = i + j; k++;But really, when you want to add one to an expression, just use
i + j + 1Another unfortunate (and utterly meaningless) example is i = i++;If you want to increment i (that is, add one to it, and store the result back in i), either use
i = i + 1;or
i++;Don't try to combine the two.
page 47 Deep sentence:
In a context where no value is wanted, just the incrementing effect, as in
if(c == '\n') nl++;prefix and postfix are the same.
In other words, when you're just incrementing some variable, you can use either the nl++ or ++nl form. But when you're immediately using the result, as in the examples we'll look at later, using one or the other makes a big difference.
In that light, study one of the examples on this page--squeeze, the modified getline, or strcat--and convince yourself that it would not work if the wrong form of increment (++i or ++j) were used. You may note that all three examples on pages 47-48 use the postfix form. Postfix increment is probably more common, though prefix definitely has its uses, too.
You may notice the keyword void popping up in a few code examples. void is a type we haven't met yet; it's a type with no values and no operations. When a function is declared as ``returning'' void, as in the squeeze and strcat examples on pages 47 and 48, it means that the function does not return a value. (This was briefly mentioned on page 30 in chapter 1.)
No comments:
Post a Comment