< previous page page_516 next page >

Page 516
Here is another example. The absolute value of a number x is defined as
0516-01.gif
To compute the absolute value of a variable x and store it into y, you could use the ?: operator as follows:
y = (x >= 0) ? x : -x;
In both the max and the absolute value examples, we used parentheses around the expression being tested. These parentheses are unnecessary because, as we'll see shortly, the conditional operator has very low precedence. But it is customary to include the parentheses for clarity.
Operator Precedence
Below is a summary of operator precedence for the C++ operators that we have encountered so far, excluding the bitwise operators. (Appendix B contains the complete list.)
Precedence (highest to lowest)
Operator
Associativity
()
Left to right
unary:
++ -- ! + - (cast) sizeof
Right to left
* / %
Left to right
+ -
Left to right
< <= > >=
Left to right
== !=
Left to right
&&
Left to right
||
Left to right
?:
Right to left
= += -= etc.
Right to left

The column labeled Associativity describes grouping order. Within a precedence level, most operators group from left to right. For example,
a - b + c
means
(a - b) + c
and not
a - (b + c)
Certain operators, though, group from right to left. Look at the assignment operators, for example. The expression

 
< previous page page_516 next page >