|
The increment (++) and decrement (--) operators provide a convenient notational shorthand for adding or subtracting 1 from an object. There are two forms of these operators: prefix and postfix. So far, we have used only the prefix increment, which increments its operand and yields the changed value as its result. The prefix decrement operates similarly, except that it decrements its operand. The postfix versions of these operators increment (or decrement) the operand but yield a copy of the original, unchanged value as its result:
注意:递增与递减操作符除了有值,还有副作用。这两个操作符会改变操作数本身的值。
从语法上说,++ 和--是一个字元(token),不能分开写。分开写的话相当于两个一元+ 或- 操作符。 - int i = 0, j;
- j = ++i;
j = i++;
Because the prefix version returns the incremented value, it returns the object itself as an lvalue. The postfix versions return an rvalue.
注意:C++(www.cppentry.com) 规定前缀递增操作符返回的是左值,这与C 语言的规定不同。
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 does less 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. For ints and pointers, the compiler can optimize away this extra work. For more complex iterator types, this extra work potentially could be more costly. By habitually favoring the use of the prefix versions, we do not have to worry if the performance difference matters.
Postfix Operators Return the Unincremented Value
The postfix version of ++ and -- is used most often when we want to use the current value of a variable and increment it in a single compound expression: - vector<int> ivec;
- int cnt = 10;
-
- while (cnt > 0)
- ivec.push_back(cnt--);
|