Datasheet
Operator Description Usage
!= Not equals. The result of if (i != 3) {
the statement is true if the std::cout << “i is not 3”;
left-hand side does not }
equal the right-hand side.
! Logical not. Negates the if (!someBoolean) {
true/false status of a std::cout << “someBoolean is false”;
Boolean expression. }
This is a unary operator.
&& Logical and. The result if (someBoolean && someOtherBoolean) {
is true if both parts of the std::cout << “both are true”;
expression are true. }
|| Logical or. The result is if (someBoolean || someOtherBoolean) {
true if either part of the std::cout << “at least one is true”;
expression is true. }
C++ uses short-circuit logic when evaluating an expression. That means that once the final result is cer-
tain, the rest of the expression won’t be evaluated. For example, if you are doing a logical or of several
Boolean expressions as shown below, the result is known to be true as soon as one of them is found to be
true. The rest won’t even be checked.
bool result = bool1 || bool2 || (i > 7) || (27 / 13 % i + 1) < 2;
In the example above, if bool1 is found to be true, the entire expression must be true, so the other parts
aren’t evaluated. In this way, the language saves your code from doing unnecessary work. It can, how-
ever, be a source of hard-to-find bugs if the later expressions in some way influence the state of the pro-
gram (for example, by calling a separate function). The following code shows a statement using
&& that
will short-circuit after the second term because 1 always evaluates to
true.
bool result = bool1 && 1 && (i > 7) && !done;
Loops
Computers are great for doing the same thing over and over. C++ provides three types of looping
structures.
The While Loop
while loops let you perform a block of code repeatedly as long as an expression evaluates to true. For
example, the following completely silly code will output “This is silly.” five times.
int i = 0;
while (i < 5) {
std::cout << “This is silly.” << std::endl;
i++;
}
14
Chapter 1
04_574841 ch01.qxd 12/15/04 3:39 PM Page 14










