
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
136
|
Chapter 5: Operators
expression month != 0 && day != 1 would exclude our users on the first day of any
month, not just January 1. This is hardly what we intended.
It’s much easier to check if today is January 1:
month = = 0 && day = = 1
This expression yields true only on the first day of January. Once we’ve gotten that
far, all we need is the NOT operator to determine when today is not January 1:
!(month= =0 && day= =1)
Obviously, this code’s intent is much clearer than the month + day > 1 test used in
Example 5-5.
Another typical usage of the NOT operator is to toggle a variable from
true to false
and vice versa. For example, suppose you have a single button that is used to turn
the sound on and off. You might use code like this:
soundState = !soundState // Reverse the current sound state
if (soundState) {
// If sound is turned on, make sure sounds are audible
} else {
// If the sound is off, set the volume to 0 to mute it
}
Notice that ! is also used in the inequality operator (!=). As a programming token (i.e.,
symbol), the
! character usually means not,oropposite. It is unrelated to the ! symbol
used to indicate “factorial” in common mathematical notation.
The Grouping Operator
Aside from being used in function calls, parentheses—( )—can also be used to group
a phrase of code to override ...