设为首页 加入收藏

TOP

5.4.3 Compound Assignment Operators
2013-10-07 15:24:36 来源: 作者: 【 】 浏览:52
Tags:5.4.3 Compound Assignment Operators

We often apply an operator to an object and then reassign the result to that same object. As an example, consider the sum program from page 14:

  1. int sum = 0;  
  2. // sum values from 1 up to 10 inclusive  
  3. for (int val = 1; val <= 10; ++val)  
  4. sum += val; // equivalent to sum = sum + val 

This kind of operation is common not just for addition but for the other arithmetic operators and the bitwise operators. There are compound assignments for each of these operators. The general syntactic form of a compound assignment operator is

  1. a op= b; 

where op= may be one of the following ten operators:

  1. += -= *= /= %= // arithmetic operators  
  2. <<= >>= &= ^= |= // bitwise operators 

Each compound operator is essentially equivalent to

  1. a = a op b; 

There is one important difference: When we use the compound assignment, the left-hand operand is eva luated only once. If we write the similar longer version, that operand is eva luated twice: once as the right-hand operand and again as the left. In many, perhaps most, contexts this difference is immaterial aside from possible performance consequences.

注意:复合赋值操作符不包括“ 逻辑与(&&)”和“ 逻辑或(||)”, 即 a =a && b 不能写成a &&= b。另外,等号之前不能有空格。

EXERCISES SECTION 5.4.3

Exercise 5.13: The following assignment is illegal. Why How would you correct it

  1. double dval; int ival; int *pi;  
  2. dval = ival = pi = 0; 

Exercise 5.14: Although the following are legal, they probably do not behave as the programmer expects. Why Rewrite the expressions as you think they should be.

(a) if (ptr = retrieve_pointer() != 0)
(b) if (ival = 1024)
(c) ival += ival + 1;

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇5.10 eva luating Compound Expre.. 下一篇5.12.6 Named Casts (2)

评论

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

·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)