Operator Precedence

In complex expressions, rules of precedence determine the order in which operations are performed. Precedence of operators

Operators Precedence not first (highest)

  • div, mod, and, shl, shr, assecond +, -, or, xor third
  • lt;>, <, >, <=, >=, in, is fourth (lowest)

An operator with higher precedence is evaluated before an operator with lower precedence, while operators of equal precedence associate to the left. Hence the expression

multiplies y times z, then adds X to the result; * is performed first, because is has a higher precedence than +. But

first subtracts y from X, then adds z to the result; - and + have the same precedence, so the operation on the left is performed first.

You can use parentheses to override these precedence rules. An expression within parentheses is evaluated first, then treated as a single operand. For example,

multiplies Z times the sum of X and Y.

Parentheses are sometimes needed in situations where, at first glance, they seem not to be. For example, consider the expression

The intended interpretation of this is obviously

Without parentheses, however, the compiler follows operator precedence rules and reads it as

which results in a compilation error unless Z is Boolean.

Parentheses often make code easier to write and to read, even when they are, strictly speaking, superfluous. Thus the first example could be written as

Here the parentheses are unnecessary (to the compiler), but they spare both programmer and reader from having to think about operator precedence.

Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment