Tuesday 8 January 2013

Precedence of operators

When writing complex expressions with several operands, we may have some doubts about which operand is
evaluated first and which later. For example, in this expression:



we may doubt if it really means:



The correct answer is the first of the two expressions, with a result of 6. There is an established order with the
priority of each operator, and not only the arithmetic ones (those whose preference come from mathematics) but
for all the operators which can appear in C++. From greatest to lowest priority, the priority order isas follows:




Grouping defines the precedence order in which operators are evaluated in the case that there are several
operators of the same level in an expression.
All these precedence levels for operators can be manipulated or become more legible by removing possible
ambiguities using parentheses signs (and ), as in this example:




might be written either as:


or

depending on the operation that we want to perform.
So if you want to write complicated expressions and you are not completely sure of the precedence levels, always
include parentheses. It will also become a code easier to read.
















No comments:

Post a Comment