Datasheet

case kSaveMenuItem:
// Code to save a file
break;
default:
// Code to give an error message
break;
}
If you omit the break statement, the code for the subsequent case will be executed whether or not it
matches. This is sometimes useful, but more frequently a source of bugs.
The Ternary Operator
C++ has one operator that takes three arguments, known as the ternary operator. It is used as a shorthand
conditional expression of the form “if [something] then [perform action], otherwise [perform some other
action]”. The ternary operator is represented by a
? and a :. The following code will output “yes” if the
variable
i is greater than 2, and “no” otherwise.
std::cout << ((i > 2) ? “yes” : “no”);
The advantage of the ternary operator is that it can occur within almost any context. In the preceding
example, the ternary operator is used within code that performs output. A convenient way to remember
how the syntax is used is to treat the question mark as though the statement that comes before it really is
a question. For example, “Is
i greater than 2? If so, the result is ‘yes’: if not, the result is ‘no.’”
Unlike an
if statement or a switch statement, the ternary operator doesn’t execute code based on the
result. Instead, it is used within code, as shown in the preceding example. In this way, it really is an oper-
ator (like
+ and -) as opposed to a true conditional, such as if and switch.
Conditional Operators
You have already seen a conditional operator without a formal definition. The > operator compares two
values. The result is “true” if the value on the left is greater than the value on the right. All conditional
operators follow this pattern they all result in a
true or false.
The table below shows other common conditional operators.
Operator Description Usage
< Determines if the left-hand side if (i <= 0) {
<=
is less than, less than or equal to, std::cout << “i is negative”;
>
greater than,or greater than or }
>=
equal to the right-hand side.
== Determines if the left-hand side if (i == 3) {
equals the right-hand side. std::cout << “i is 3”;
Don’t confuse this with the }
=
(assignment) operator!
Table continued on following page
13
A Crash Course in C++
04_574841 ch01.qxd 12/15/04 3:39 PM Page 13