|
|
|
|
|
|
|
In Chapter 3, we discussed the rules of precedence, the rules that govern the evaluation of complex arithmetic expressions. C++'s rules of precedence also govern relational and logical operators. Here's a list showing the order of precedence for the arithmetic, relational, and logical operators (with the assignment operator thrown in as well): |
|
|
|
|
|
|
|
|
Operators on the same line in the list have the same precedence. If there is more than one operator with the same precedence in an expression, most of the operators group (associate) from left to right. For example, the expression |
|
|
|
|
|
|
|
|
means (a / b) * c, not a / (b * c). However, the ! operator groups from right to left. Although you'd never have occasion to use this expression: |
|
|
|
|
|
|
|
|
the meaning of it is !(!badData) rather than the meaningless (!!)badData. Appendix B, Precedence of Operators, lists the order of precedence for all operators in C++. In skimming the appendix, you can see that a few of the operators associate from right to left (for the same reason we just described for the ! operator). |
|
|
|
|
|
|
|
|
Parentheses are used to override the order of evaluation in an expression. If you're not sure whether parentheses are necessary, use them anyway. The compiler disregards unnecessary parentheses. So if they clarify an expression, use them. Some programmers like to include extra parentheses when assigning a relational expression to a Boolean variable: |
|
|
|
|
|
|
|
|
dataInvalid = (inputVal == 0); |
|
|
|
|
|