Normally, statements in a program execute one after the other in the order in which they are written. This is called sequential execution. Various C++ statements we will soon discuss enable the programmer to specify that the next statement to execute may be other than the next one in sequence. This is called transfer of control.
During the 1960s, it became clear that the indiscriminate use of transfers of control was the root of much difficulty experienced by software development groups. The finger of blame was pointed at the goto statement, which allows the programmer to specify a transfer of control to one of a wide range of possible destinations in a program (creating what is often called "spaghetti code"). The notion of so-called structured programming became almost synonymous with "goto elimination."
The research of Böhm and Jacopini[1] demonstrated that programs could be written without any goto statements. It became the challenge of the era for programmers to shift their styles to "goto-less programming." It was not until the 1970s that programmers started taking structured programming seriously. The results have been impressive, as software development groups have reported reduced development times, more frequent ontime delivery of systems and more frequent within-budget completion of software projects. The key to these successes is that structured programs are clearer, are easier to debug, test and modify and are more likely to be bug-free in the first place.
[1] Böhm, C., and G. Jacopini, "Flow Diagrams, Turing Machines, and Languages with Only Two Formation Rules," Communications of the ACM, Vol. 9, No. 5, May 1966, pp. 366371.
Böhm and Jacopini's work demonstrated that all programs could be written in terms of only three control structures, namely, the sequence structure, the selection structure and the repetition structure. The term "control structures" comes from the field of computer science. When we introduce C++'s implementations of control structures, we will refer to them in the terminology of the C++ standard document[2] as "control statements."
[2] This document is more specifically known as NCITS/ISO/IEC 14882-2003 Programming languagesC++ and is available for download (for a fee) at: webstore.ansi.org/ansidocstore/product.asp?sku=INCITS%2FISO%2FIEC+14882%2D2003.
Sequence Structure in C++
The sequence structure is built into C++. Unless directed otherwise, the computer executes C++ statements one after the other in the order in which they are writtenthat is, in sequence. The Unified Modeling Language (UML) activity diagram of Fig. 4.2 illustrates a typical sequence structure in which two calculations are performed in order. C++ allows us to have as many actions as we want in a sequence structure. As we will soon see, anywhere a single action may be placed, we may place several actions in sequence.
Figure 4.2. Sequence-structure activity diagram.
In this figure, the two statements involve adding a grade to a total variable and adding the value 1 to a counter variable. Such statements might appear in a program that takes the average of several student grades. To calculate an average, the total of the grades being averaged is divided by the number of grades. A counter variable would be used to keep track of the number of values being averaged. You will see similar statements in the program of Section 4.8.
Activity diagrams are part of the UML. An activity diagram models the workflow (also called the activity) of a portion of a software system. Such workflows may include a portion of an algorithm, such as the sequence structure in Fig. 4.2. Activity diagrams are composed of special-purpose symbols, such as action state symbols (a rectangle with its left and right sides replaced with arcs curving outward), diamonds and small circles; these symbols are connected by transition arrows, which represent the flow of the activity.
Like pseudocode, activity diagrams help programmers develop and represent algorithms, although many programmers prefer pseudocode. Activity diagrams clearly show how control structures operate.
Consider the sequence-structure activity diagram of Fig. 4.2. It contains two action states that represent actions to perform. Each action state contains an action expressione.g., "add grade to total" or "add 1 to counter"that specifies a particular action to perform. Other actions might include calculations or input/output operations. The arrows in the activity diagram are called transition arrows. These arrows represent transitions, which indicate the order in which the actions represented by the action states occurthe program that implements the activities illustrated by the activity diagram in Fig. 4.2 first adds grade to total, then adds 1 to counter.
The solid circle located at the top of the activity diagram represents the activity's initial statethe beginning of the workflow before the program performs the modeled activities. The solid circle surrounded by a hollow circle that appears at the bottom of the activity diagram represents the final statethe end of the workflow after the program performs its activities.
Figure 4.2 also includes rectangles with the upper-right corners folded over. These are called notes in the UML. Notes are explanatory remarks that describe the purpose of symbols in the diagram. Notes can be used in any UML diagramnot just activity diagrams. Figure 4.2 uses UML notes to show the C++ code associated with each action state in the activity diagram. A dotted line connects each note with the element that the note describes. Activity diagrams normally do not show the C++ code that implements the activity. We use notes for this purpose here to illustrate how the diagram relates to C++ code. For more information on the UML, see our optional case study, which appears in the Software Engineering Case Study sections at the ends of Chapters 17, 9, 10, 12 and 13, or visit www.uml.org.
Selection Statements in C++
C++ provides three types of selection statements (discussed in this chapter and Chapter 5). The if selection statement either performs (selects) an action if a condition (predicate) is true or skips the action if the condition is false. The if...else selection statement performs an action if a condition is true or performs a different action if the condition is false. The switch selection statement (Chapter 5) performs one of many different actions, depending on the value of an integer expression.
The if selection statement is a single-selection statement because it selects or ignores a single action (or, as we will soon see, a single group of actions). The if...else statement is called a double-selection statement because it selects between two different actions (or groups of actions). The switch selection statement is called a multiple-selection statement because it selects among many different actions (or groups of actions).
Repetition Statements in C++
C++ provides three types of repetition statements (also called looping statements or loops) that enable programs to perform statements repeatedly as long as a condition (called the loop-continuation condition) remains true. The repetition statements are the while, do...while and for statements. (Chapter 5 presents the do...while and for statements.) The while and for statements perform the action (or group of actions) in their bodies zero or more timesif the loop-continuation condition is initially false, the action (or group of actions) will not execute. The do...while statement performs the action (or group of actions) in its body at least once.
Each of the words if, else, switch, while, do and for is a C++ keyword. These words are reserved by the C++ programming language to implement various features, such as C++'s control statements. Keywords must not be used as identifiers, such as variable names. Figure 4.3 contains a complete list of C++ keywords.
C++ Keywords |
||||
---|---|---|---|---|
Keywords common to the C and C++ programming languages |
||||
auto |
break |
case |
char |
const |
continue |
default |
do |
double |
else |
enum |
extern |
float |
for |
goto |
if |
int |
long |
register |
return |
short |
signed |
sizeof |
static |
struct |
switch |
typedef |
union |
unsigned |
void |
volatile |
while |
|||
C++-only keywords |
||||
and |
and_eq |
asm |
bitand |
bitor |
bool |
catch |
class |
compl |
const_cast |
delete |
dynamic_cast |
explicit |
export |
false |
friend |
inline |
mutable |
namespace |
new |
not |
not_eq |
operator |
or |
or_eq |
private |
protected |
public |
reinterpret_cast |
static_cast |
template |
this |
throw |
true |
try |
typeid |
typename |
using |
virtual |
wchar_t |
xor |
xor_eq |
Common Programming Error 4.1
Using a keyword as an identifier is a syntax error. |
Common Programming Error 4.2
Spelling a keyword with any uppercase letters is a syntax error. All of C++'s keywords contain only lowercase letters. |
Summary of Control Statements in C++
C++ has only three kinds of control structures, which from this point forward we refer to as control statements: the sequence statement, selection statements (three typesif, if...else and switch) and repetition statements (three typeswhile, for and do...while). Each C++ program combines as many of these control statements as is appropriate for the algorithm the program implements. As with the sequence statement of Fig. 4.2, we can model each control statement as an activity diagram. Each diagram contains an initial state and a final state, which represent a control statement's entry point and exit point, respectively. These single-entry/single-exit control statements make it easy to build programsthe control statements are attached to one another by connecting the exit point of one to the entry point of the next. This is similar to the way a child stacks building blocks, so we call this control-statement stacking. We will learn shortly that there is only one other way to connect control statementscalled control-statement nesting, in which one control statement is contained inside another. Thus, algorithms in C++ programs are constructed from only three kinds of control statements, combined in only two ways. This is the essence of simplicity.
Software Engineering Observation 4.1
Any C++ program we will ever build can be constructed from only seven different types of control statements (sequence, if, if...else, switch, while, do...while and for) combined in only two ways (control-statement stacking and control-statement nesting). |
Introduction to Computers, the Internet and World Wide Web
Introduction to C++ Programming
Introduction to Classes and Objects
Control Statements: Part 1
Control Statements: Part 2
Functions and an Introduction to Recursion
Arrays and Vectors
Pointers and Pointer-Based Strings
Classes: A Deeper Look, Part 1
Classes: A Deeper Look, Part 2
Operator Overloading; String and Array Objects
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Polymorphism
Templates
Stream Input/Output
Exception Handling
File Processing
Class string and String Stream Processing
Web Programming
Searching and Sorting
Data Structures
Bits, Characters, C-Strings and structs
Standard Template Library (STL)
Other Topics
Appendix A. Operator Precedence and Associativity Chart
Appendix B. ASCII Character Set
Appendix C. Fundamental Types
Appendix D. Number Systems
Appendix E. C Legacy Code Topics
Appendix F. Preprocessor
Appendix G. ATM Case Study Code
Appendix H. UML 2: Additional Diagram Types
Appendix I. C++ Internet and Web Resources
Appendix J. Introduction to XHTML
Appendix K. XHTML Special Characters
Appendix L. Using the Visual Studio .NET Debugger
Appendix M. Using the GNU C++ Debugger
Bibliography