设为首页 加入收藏

TOP

5.10.2 Associativity
2013-10-07 15:26:20 来源: 作者: 【 】 浏览:68
Tags:5.10.2 Associativity

Associativity specifies how to group operators at the same precedence level. We have also seen cases where associativity matters. As one example, the assignment operator is right associative. This fact allows concatenated assignments:

  1. ival = jval = kval = lval // right associative  
  2. (ival = (jval = (kval = lval))) // equivalent, parenthesized version 

This expression first assigns lval to kval, then the result of that to jval, and finally the result of that to ival.

The arithmetic operators, on the other hand, are left associative. The expression

  1. ival * jval / kval * lval // left associative  
  2. (((ival * jval) / kval) * lval) // equivalent, parenthesized version 

multiplies ival and jval, then divides that result by kval, and finally multiplies the result of the division by lval.

 

 

Table 5.4 presents the full set of operators ordered by precedence. The table is organized into segments separated by double lines. Operators in each segment have the same precedence, and have higher precedence than operators in subsequent segments. For example, the prefix increment and dereference operators share the same precedence and have higher precedence than the arithmetic or relational operators. We have seen most of these operators, although a few will not be defined until later chapters.

EXERCISES SECTION 5.10.2

Exercise 5.25: Using Table 5.4 (p. 170), parenthesize the following expressions to indicate the order in which the operands are grouped:

(a) ! ptr == ptr->next

(b) ch = buf[ bp++ ] != ’\n’

Exercise 5.26: The expressions in the previous exercise eva luate in an order that is likely to be surprising. Parenthesize these expressions to eva luate in an order you imagine is intended.

Exercise 5.27: The following expression fails to compile due to operator precedence. Using Table 5.4 (p. 170), explain why it fails. How would you fix it

  1. string s = "word";  
  2. // add an ‘s’ to the end, if the word doesn’t already end in ‘s’  
  3. string pl = s + s[s.size() - 1] == ’s’   "" : "s" ; 
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2.6 Typedef Names 下一篇5.10.1 Precedence

评论

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

·如何利用Python做数 (2025-12-24 23:48:36)
·如何使用python进行 (2025-12-24 23:48:34)
·python 爬虫入门该怎 (2025-12-24 23:48:31)
·Java 实现多个大文件 (2025-12-24 23:22:00)
·Java多线程编程在工 (2025-12-24 23:21:56)