Operator Precedence
The compiler must know the order in which to evaluate a series of operators. For example, if you write:
myVariable = 5 + 7 * 3;
there are three operators for the compiler to evaluate (=, +, and *). It could, for example, operate left to right, which would assign the value 5 to myVariable, then add 7 to the 5 (12) and multiply by 3 (36)—but of course, then it would throw that 36 away. This is clearly not what is intended.
The rules of precedence tell the compiler which operators to evaluate first. As is the case in algebra, multiplication has higher precedence than addition, so 5+7 x 3 is equal to 26 rather than 36. Both multiplication and addition have higher precedence than assignment, so the compiler will do the math and then assign the result (26) to myVariable only after the math is completed.
In C#, you can also use parentheses to change the order of precedence much as you would in algebra. Thus, you can change the result by writing:
myVariable = (5+7) * 3;
Grouping the elements of the assignment in this way causes the compiler to add 5+7, multiply the result by 3, and then assign that value (36) to myVariable.
Table 4-3 summarizes operator precedence in C#, using x and y as possible terms to be operated upon.[1]
Table 4-3. Operator precedence
Category | Operators |
|---|---|
Primary |
|
Unary |
|
Multiplicative |
|
Additive |
|
Shift |
|
Relational |
|
Equality |
|
Logical (bitwise) ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access