Is there a type in the .NET Framework that will compare two operators and determine if one has lower precedence than another? For the time being, I've implemented a function in the form of IComparer<ExpressionType>
, for the operators I am interested in, and by using the operator category chart for the C# language.
The implementation is trivial, and of general use for compiler/interpreter implementers, leading me to think that a general utility function exists. Alternatively, it would also be trivial to implement such a comparer if a library function exists to get the ordinal of a given operator.
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-- .
Operators with the same precedence are evaluated from left to right. To override the normal order of evaluation in an expression, use parentheses. Subexpressions in parentheses are evaluated before the other parts of the expression, from left to right.
When two operators share an operand and the operators have the same precedence, then the expression is evaluated according to the associativity of the operators. For example, since the ** operator has right-to-left associativity, a ** b ** c is treated as a ** (b ** c) .
The assignment operators have the lowest precedence while the postfix increment and decrement operators have the highest precedence.
No, there isn't, and you've mentioned why (emphasis mine):
I've implemented a function in the form of
IComparer<ExpressionType>
, for the operators I am interested in, and by using the operator category chart for the C# language.
Operator overloading precedence is a language-specific detail. The Base Class Libraries (BCL) and the CLR are language-agnostic, they support many languages, all of which can provide their own order for operator precedence.
And even if they offered a method to be used in any language to indicate what the operator overload precedence would be, what happens when you write code in language A (with precedence PA) and then consume it with language B (with precedence PB)?
You would get inconsistent results.
This is why it's determined on the language level, and not on the BCL/CLR level; there's just no possible way to do it consistently across languages, and it might not even make sense if they could or tried given that you can access the library from multiple languages.
If you are going to implement such a thing, I recommend that you include a language identifier and make sure that comparisons of operator precedence are tied to the language. That's the only way to guarantee consistent results when the method/library is used across all languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With