Datasheet
cout << “Employee: “ << anEmployee.firstInitial <<
anEmployee.middleInitial <<
anEmployee.lastInitial << endl;
cout << “Number: “ << anEmployee.employeeNumber << endl;
cout << “Salary: $” << anEmployee.salary << endl;
return 0;
}
Conditionals
Conditionals let you execute code based on whether or not something is true. There are three main types
of conditionals in C++.
If/Else Statements
The most common conditional is the if statement, which can be accompanied by else. If the condition
given inside the
if statement is true, the line or block of code is executed. If not, execution continues to
the
else case if present, or to the code following the conditional. The following pseudocode shows a cas-
cading if statement, a fancy way of saying that the
if statement has an else statement that in turn has
another
if statement, and so on.
if (i > 4) {
// Do something.
} else if (i > 2) {
// Do something else.
} else {
// Do something else.
}
The expression between the parentheses of an if statement must be a Boolean value or evaluate to a
Boolean value. Conditional operators, described below, provide ways of evaluating expressions to result
in a
true or false Boolean value.
Switch Statements
The switch statement is an alternate syntax for performing actions based on the value of a variable. In
switch statements, the variable must be compared to a constant, so the greater-than if statements
above could not be converted to switch statements. Each constant value represents a “case”. If the vari-
able matches the case, the subsequent lines of code are executed until the
break statement is reached.
You can also provide a
default case, which is matched if none of the other cases match.
switch statements are generally used when you want to do something based on the specific value of a
variable, as opposed to some test on the variable. The following pseudocode shows a common use of the
switch statement.
switch (menuItem) {
case kOpenMenuItem:
// Code to open a file
break;
12
Chapter 1
04_574841 ch01.qxd 12/15/04 3:39 PM Page 12