【问题标题】:Why does a unary operator have associativity为什么一元运算符具有结合性
【发布时间】:2015-05-08 15:13:06
【问题描述】:

在像“10 - 3 - 2”这样的表达式中,很容易理解为什么 - 和 + 运算符是关联的。为了匹配数学约定,结果是 5 而不是 9。据我了解,关联性是指某些运算符具有相同优先级时的顺序。

但这与一元运算符有什么关系?我不明白为什么一元运算符具有关联性。

注意:该问题是关于一般编程的,但如果您必须以与语言相关的方式回答,则首选 C。

【问题讨论】:

标签: expression operator-keyword associativity compiler-construction


【解决方案1】:
**Arithmetic Operators** (Left-to-Right)
+   Additive operator (a + b)
-   Subtraction operator (a - b)
*   Multiplication operator (a * b)
/   Division operator (a / b)
%   Remainder operator (a % b)

**Unary operators** (Right-to-Left)
+   Unary plus operator; indicates positive value (numbers are positive without this, however) 
-   Unary minus operator; negates an expression
++  Increment operator; increments a value by 1
--  Decrement operator; decrements a value by 1
!   Logical complement operator; inverts the value of a boolean

但是当我们考虑一元例如:

a = +1
a= -1
a++
a-- etc

您在此处使用10 - 3 - 2 提到的内容不会被纳入一元运算。

So the operation will be Left-to-Right. Therefore:
10 - 3 equals 7 then
7 - 2 equals 5

Not as given below (Arithmetic operators always Left-to-Right not Right-to-Left)
3 - 2 = 1 then
10 - 1 = 9 This is absolutely wrong.

更多详情,请查看以下参考:

  1. Precedence and Associativity
  2. Assignment, Arithmetic, and Unary Operators(我对C语言接触不多。但是运算符很常见。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    • 2011-09-23
    • 2023-03-13
    • 2010-10-18
    • 2013-05-14
    相关资源
    最近更新 更多