< Previous | Contents | Next >
Understanding Order of Operations
Just like arithmetic operators, logical operators have precedence levels that affect the order in which an expression is evaluated. Logical NOT, !, has a higher level of precedence than logical AND, &&, which has a higher precedence than logical OR, ||.
Just as with arithmetic operators, if you want an operation with lower precedence to be evaluated first, you can use parentheses. You can create complex expressions that involve arithmetic operators, relational operators, and logical operators. Operator precedence will define the exact order in which elements of the expression are evaluated. However, it’s best to try to create expressions that are clear and simple, not ones that require a mastery of the operator precedence list to decipher.
For a list of C++ operators and their precedence levels, see Appendix B.
68 Chapter 2 n Truth, Branching, and the Game Loop: Guess My Number
Hi n t
Although you can use parentheses in a larger expression to change the way in which it’s evaluated, you can also use redundant parentheses—parentheses that don’t change the value of the expressions—to make the expression clearer. Let me give you a simple example. Check out the following expression from the Designers Network program:
(username == "S.Meier" && password == "civilization")
Now, here’s the expression with some redundant parentheses:
( (username == "S.Meier") && (password == "civilization") )
While the extra parentheses don’t change the meaning of the expression, they really help the two smaller expressions, joined by the && operator, stand out.
Using redundant parentheses is a bit of an art form. Are they helpful or just plain redundant? That’s a call you as the programmer have to make.