Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 692
sawa Avatar asked Feb 23 '14 19:02

sawa


People also ask

Which unary operator has highest precedence?

The first line has the highest precedence. Lary Huang has told me that the postfix unary -- and postfix unary ++ have a higher precedence than the prefix unary -- and prefix unary ++.

What is the order of precedence for operators?

The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .

Which has highest precedence ++ or ()?

Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator: For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.


Video Answer


1 Answers

My programming ruby book (2nd edition) also lists unary operators as having higher precedence than assignment.

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.

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.

like image 137
iheggie Avatar answered Oct 05 '22 02:10

iheggie