设为首页 加入收藏

TOP

5.5 Increment and Decrement Operators (1)
2013-10-07 15:23:44 来源: 作者: 【 】 浏览:66
Tags:5.5 Increment and Decrement Operators

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),不能分开写。分开写的话相当于两个一元+ 或- 操作符。

  1. int i = 0, j;  
  2. j = ++i; // j = 1, i = 1: prefix yields incremented value  
  3. j = i++; // j = 1, i = 2: postfix yields unincremented value 

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:

  1. vector<int> ivec; // empty vector  
  2. int cnt = 10;  
  3. // add elements 10...1 to ivec  
  4. while (cnt > 0)  
  5. ivec.push_back(cnt--); // int postfix decrement 
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇5.5 Increment and Decrement Ope.. 下一篇5.4.2 Assignment Has Low Preced..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Sphinx : 高性能SQL (2025-12-24 10:18:11)
·Pandas 性能优化 - (2025-12-24 10:18:08)
·MySQL 索引 - 菜鸟教 (2025-12-24 10:18:06)
·Shell 基本运算符 - (2025-12-24 09:52:56)
·Shell 函数 | 菜鸟教 (2025-12-24 09:52:54)