C Sharp

Operator Precedence

When a single expression or statement contains multiple operators, the compiler must determine the order in which these different operators will be evaluated. The rules that govern how the complier makes this determination are called operator precedence. Understanding operator precedence can mean the difference between writing your expressions with confidence and staring at a single line of code as you wonder why the result isn't what you think it should be.

Take a look at the following expression: 42 + 6 * 10. If you add 42 and 6 and then multiply the sum by 10, the product is 480. If you multiply 6 and 10 and then add that product to 42, the result is 102. When code is compiled, a special part of the compiler called the lexical analyzer is responsible for determining how this code should be read. It's the lexical analyzer that determines the relative precedence of operators when more than one kind of operator is present in an expression. It does this by specifying a value (or precedence) for each supported operator. The higher precedence operators are resolved first. In our example, the * operator has a higher precedence than the + operator because * takes-more on this term in a moment-its operands before + does. The reason for this comes from the basic rules of arithmetic: multiplication and division always have higher precedence than addition and subtraction. So, back to the example: 6 is said to be taken by the * in both 42 + 6 * 10 and 42 * 6 + 10 such that these expressions are the equivalent of 42 + (6 * 10) and (42 * 6) + 10.

How C# Determines Precedence

Let's look specifically at how C# assigns precedence to operators. Table 10-1 illustrates C# operator precedence from highest precedence to lowest precedence. After this section, I'll go into more detail on the different categories of operators that are supported in C#.

Table 10-1 C# Operator Precedence
Category of Operator
Operators
Primary
(x), x.y, f(x), a[x], x++, x--, new, typeof, sizeof, checked, unchecked
Unary
+, -, !, ~, ++x, --x, (T)x
Multiplicative
*, /, %
Additive
+, -
Shift
<<, >>
Relational
<, >, <=, >=, is
Equality
==
Logical AND
&
Logical XOR
^
Logical OR
|
Conditional AND
&&
Conditional OR
||
Conditional
?:
Assignment
=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=

by BrainBellupdated
Advertisement: