一元运算符的运算符优先级 [英] Operator precedence of unary operators
问题描述
关于运算符优先级的某些信息来源像这样表示,一元运算符如!
,~
, +
,-
的优先级比任务=
高.但是,可以使用以下表达式:
Some information source on operator precedence like this says that unary operators like !
, ~
, +
, -
have higher precedence than assignment =
. However, the following expressions are possible:
!a = true # => false (with warning)
a # => true
~a = 1 # => -2
a # => 1
+a = 1 # => 1
a # => 1
-a = 1 # => -1
a # => 1
考虑到这些结果,我能想到的唯一可能的解释是,这些一元运算符的优先级比赋值的优先级低.如果真是这样,那就意味着我上面提到的信息是错误的.哪个是正确的?有不同的解释吗?
Considering these results, the only possible explanation I can think of is that these unary operator have lower precedence than the assignment. If that is the case, then it would mean that the information I mentioned above is wrong. Which is correct? Is there a different explanation?
推荐答案
我的编程红宝石书(第2版)还列出了一元运算符的优先级高于赋值的优先级.
My programming ruby book (2nd edition) also lists unary operators as having higher precedence than assignment.
一元运算符的优先级最高.该行被解析为〜(a = 1)的原因是因为将行分解为有效语法比其他任何事物都具有更高的优先级,包括使用简单变量'a'作为一元运算符对其进行操作的表达式.
The unary operator IS being given highest precedence. The reason the line is parsed as ~ (a = 1) is because decomposing the line into valid syntax is of higher precedence than anything else, including using the simple variable 'a' as the expression the unary operator operates on.
如果ruby解析器可以使其余部分有效,它将使用(〜a),但是没有有效的规则,而matches = something,只有左值'='rvalue.
If the ruby parser could have made something valid of the rest of the line, it would have used (~ a), but there is no valid rule than matches = something, only lvalue '=' rvalue.
您可以将有效语法"放在首位,然后是简单值,常量和变量名,然后是其下的标准运算符.
You can regard "valid syntax" as the top priority, then simple values, constant and variable names and then the standard operators under that.
这篇关于一元运算符的运算符优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!