Operator precedence examples. Unary and binary.

300 Views Asked by At

I have a question on operator precedence it comes from a compiler implementation that I'm doing. I'm told that i should implement the following order of precedence:

new, . , [] , ! , * , + , < ,== , ||

where . stands for method a call and [] for an array read. I just realized that new,.,[], ! are unary operators while others are binary.

For binary operators I have clear examples of what operator precedence means. For example:

expr1 + expr2 * expr3

If we say that * has more precedence than + that means that in my parse tree * expr should be deduced first and then a + expr should be deduced. It is clear that if we establish that precedence works the other way around then we get actually different parse trees.

So, I ask you to provide examples of operator precedence of

  • two unary operators
  • one unary operator and one binary operator

In these examples it should be clear that if we changed precedence order then we would get different parse trees.

1

There are 1 best solutions below

0
On BEST ANSWER

Two unary operators: !a[0] means !(a[0]), not (!a)[0].

Unary and binary: !a || b means (!a) || b, not !(a || b).

In cases such as a[0].foo or a || !b there is of course no ambiguity, and precedence specifications will be superfluous. Precedence between two unary operators can matter only of one is prefix and the other is postfix.

It is somewhat unusual in programming languages to have unary operators that bind weaker than binary ones. Lambda bindings are an example: $\lambda x.xy$ means $\lambda x.(xy)$ not $(\lambda x.x)y$.