设为首页 加入收藏

TOP

5.4.2 Assignment Has Low Precedence
2013-10-07 15:23:38 来源: 作者: 【 】 浏览:67
Tags:5.4.2 Assignment Has Low Precedence

Inside a condition is another common place where assignment is used as a part of a larger expression. Writing an assignment in a condition can shorten programs and clarify the programmer’s intent. For example, the following loop uses a function named get_value, which we assume returns int values. We can test those values until we obtain some desired value—say, 42:

  1. int i = get_value(); // get_value returns an int  
  2. while (i != 42) {  
  3. // do something ...  
  4. i = get_value();  

The programbegins by getting the first value and storing it in i. Then it establishes the loop, which tests whether i is 42, and if not, does some processing. The last statement in the loop gets a value from get_value(), and the loop repeats. We can write this loop more succinctly as

  1. int i;  
  2. while ((i = get_value()) != 42) {  
  3. // do something ...  

The condition now more clearly expresses our intent: We want to continue until get_value returns 42. The condition executes by assigning the result returned by get_value to i and then comparing the result of that assignment with 42.

The additional parentheses around the assignment are necessary because assignment has lower precedence than inequality.

Without the parentheses, the operands to != would be the value returned from calling get_value and 42. The true or false result of that test would be assigned to i—clearly not what we intended!

Beware of Confusing Equality and Assignment Operators The fact that we can use assignment in a condition can have surprising effects:

if (i = 42)

This code is legal: What happens is that 42 is assigned to i and then the result of the assignment is tested. In this case, 42 is nonzero, which is interpreted as a true value. The author of this code almost surely intended to test whether i was 42:

if (i == 42)

Bugs of this sort are notoriously difficult to find. Some, but not all, compilers are kind enough to warn about code such as this example.

EXERCISES SECTION 5.4.2

Exercise 5.11: What are the values of i and d after the each assignment:

  1. int i; double d;  
  2. d = i = 3.5;  
  3. i = d = 3.5; 

出现这种错误的根本原因是C++(www.cppentry.com) 让“赋值”成为表达式。好在现在的编译器大多能帮我们发现这种低级错误。[CCS, item 1] :在最高警告级别下干净地编译。

Exercise 5.12: Explain what happens in each of the if tests:

  1. if (42 = i) // . . .  
  2. if (i = 42) // . . . 
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇5.5 Increment and Decrement Ope.. 下一篇5.4.1 Assignment Is Right Assoc..

评论

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

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