< Previous | Contents | Next >
The logical OR operator, ||, lets you join two expressions to form a larger one, which can be evaluated to true or false. The new expression is true if the first
66 Chapter 2 n Truth, Branching, and the Game Loop: Guess My Number
expression or the second expression is true; otherwise, it is false. Just as in English, “or” means either. If either the first or second expression is true, then the new expression is true. (If both are true, then the larger expression is still true.) Here’s a concrete example from the Designers Network program:
else if (username == "guest" || password == "guest")
The expression username == "guest" || password == "guest" is true if username == "guest" is true or if password == "guest" is true. This works perfectly because I want to grant a user access as a guest as long as he enters guest for the username or password. If the user enters guest for both, that’s fine too.
Another way to understand how || works is to look at all of the possible combinations of truth and falsity (see Table 2.4).
true
true
true false
true
false
true false
true
true
false false
username == "guest" ||
password == "guest"
password ==
"guest"
username ==
"guest"
Table 2.4 Possible Login Combinations Using the OR Operator