Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for precedence of instanceof/is

In both C#/Java the operator precedence of is respectively instanceof leads to some ugly necessary parenthesis. For example instead of writing if (!bar instanceof Foo) you have to write if (!(bar instanceof Foo)).

So why did the language teams decide that ! has a higher operator precedence than is/instanceof? Admittedly in C# you can overwrite operator! which would lead to a different result in some situations, but those situations seems exceedingly rare (and non-intuitive in any case), while the case of checking if something is not a type or subtype of something is much more likely.

like image 955
Voo Avatar asked Aug 23 '13 00:08

Voo


People also ask

What is the precedence of operators?

The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3 , the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary.

Which of these has highest precedence Mcq?

Explanation: Operator ++ has the highest precedence than / , * and +.

Which operator has the highest precedence level?

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-- .


1 Answers

In Java, instanceof is one of the relational operators and has the same precedence as the other ones:

RelationalExpression:
    ShiftExpression
    RelationalExpression < ShiftExpression
    RelationalExpression > ShiftExpression
    RelationalExpression <= ShiftExpression
    RelationalExpression >= ShiftExpression
    RelationalExpression instanceof ReferenceType

From that perspective it makes sense that those two lines should follow the same structure:

if (!(a instanceof b))
if (!(a < b))
like image 78
assylias Avatar answered Oct 11 '22 16:10

assylias