2 Introduction to C++ Programming, Input/Output and Operators Objectives In this chapter you’ll: ■ Write simple C++ programs. ■ Write input and output statements. ■ Use fundamental types. ■ Use arithmetic operators. ■ Learn the precedence of arithmetic operators. ■ Write decision-making statements.
40
Embed
IntroductiontoC++Programming, Input/Output and Operators · the input/output stream header.This header is a file containinginformation used by the compiler when compiling
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
2Introduction to C++ Programming,
Input/Output and Operators
O b j e c t i v e sIn this chapter you’ll:
� Write simple C++ programs.
� Write input and output statements.
� Use fundamental types.
� Use arithmetic operators.
� Learn the precedence of arithmetic operators.
� Write decision-making statements.
20 Chapter 2 Introduction to C++ Programming, Input/Output and OperatorsO
utl
ine
2.1 IntroductionWe now introduce C++ programming. We show how to display messages on the screenand obtain data from the user at the keyboard for processing. We explain how to performarithmetic calculations and save their results for later use. We demonstrate decision-makingby showing you how to compare two numbers, then display messages based on the com-parison results.
Compiling and Running ProgramsAt www.deitel.com/books/cpp11fp, we’ve posted videos that demonstrate compiling andrunning programs in Microsoft Visual C++, GNU C++ and Xcode.
2.2 First Program in C++: Printing a Line of TextConsider a simple program that prints a line of text (Fig. 2.1). This program illustrates sev-eral important features of the C++ language. The line numbers are not part of the sourcecode.
CommentsLines 1 and 2
each begin with //, indicating that the remainder of each line is a comment. The commentText-printing program describes the purpose of the program. A comment beginning with
2.1 Introduction2.2 First Program in C++: Printing a Line of
Text2.3 Modifying Our First C++ Program2.4 Another C++ Program: Adding Integers
2.5 Arithmetic2.6 Decision Making: Equality and
Relational Operators2.7 Wrap-Up
1 // Fig. 2.1: fig02_01.cpp2 // Text-printing program.3 #include <iostream> // allows program to output data to the screen45 // function main begins program execution6 int main()7 {8 std::cout << "Welcome to C++!\n"; // display message9
10 return 0; // indicate that program ended successfully11 } // end function main
2.2 First Program in C++: Printing a Line of Text 21
// is called a single-line comment because it terminates at the end of the current line. [Note:You also may use comments containing one or more lines enclosed in /* and */.]
#include Preprocessing DirectiveLine 3
is a preprocessing directive, which is a message to the C++ preprocessor (introduced inSection 1.4). Lines that begin with # are processed by the preprocessor before the programis compiled. This line notifies the preprocessor to include in the program the contents ofthe input/output stream header <iostream>. This header is a file containing informationused by the compiler when compiling any program that outputs data to the screen or in-puts data from the keyboard using C++’s stream input/output. The program in Fig. 2.1outputs data to the screen, as we’ll soon see. We discuss headers in more detail inChapter 6 and explain the contents of <iostream> in Chapter 13.
Blank Lines and White SpaceLine 4 is simply a blank line. Together, blank lines, space characters and tab characters areknown as whitespace. Whitespace characters are normally ignored by the compiler.
The main FunctionLine 5
is another single-line comment indicating that program execution begins at the next line.Line 6
is a part of every C++ program. The parentheses after main indicate that main is a programbuilding block called a function. C++ programs typically consist of one or more functionsand classes (as you’ll learn in Chapter 3). Exactly one function in every program must benamed main. Figure 2.1 contains only one function. C++ programs begin executing atfunction main, even if main is not the first function defined in the program. The keywordint to the left of main indicates that main returns an integer value. The complete list ofC++ keywords can be found in Fig. 4.2. We’ll say more about return a value when wedemonstrate how to create your own functions in Section 3.3. For now, simply includethe keyword int to the left of main in each of your programs.
The left brace, {, (line 7) must begin the body of every function. A correspondingright brace, }, (line 11) must end each function’s body.
An Output StatementLine 8
#include <iostream> // allows program to output data to the screen
Common Programming Error 2.1Forgetting to include the <iostream> header in a program that inputs data from the key-board or outputs data to the screen causes the compiler to issue an error message.
// function main begins program execution
int main()
std::cout << "Welcome to C++!\n"; // display message
22 Chapter 2 Introduction to C++ Programming, Input/Output and Operators
instructs the computer to perform an action—namely, to print the characters containedbetween the double quotation marks. Together, the quotation marks and the charactersbetween them are called a string, a character string or a string literal. In this book, werefer to characters between double quotation marks simply as strings. Whitespace charac-ters in strings are not ignored by the compiler.
The entire line 8, including std::cout, the << operator, the string "Welcome to
C++!\n" and the semicolon (;), is called a statement. Most C++ statements end with asemicolon, also known as the statement terminator (we’ll see some exceptions to thissoon). Preprocessing directives (like #include) do not end with a semicolon. Typically,output and input in C++ are accomplished with streams of characters. Thus, when thepreceding statement is executed, it sends the stream of characters Welcome to C++!\n tothe standard output stream object—std::cout—which is normally “connected” to thescreen.
The std NamespaceThe std:: before cout is required when we use names that we’ve brought into the pro-gram by the preprocessing directive #include <iostream>. The notation std::cout spec-ifies that we are using a name, in this case cout, that belongs to namespace std. The namescin (the standard input stream) and cerr (the standard error stream)—introduced inChapter 1—also belong to namespace std. Namespaces are an advanced C++ feature thatwe discuss in depth in Chapter 21, Other Topics. For now, you should simply rememberto include std:: before each mention of cout, cin and cerr in a program. This can becumbersome—the next example introduces using declarations and the using directive,which will enable you to omit std:: before each use of a name in the std namespace.
The Stream Insertion Operator and Escape SequencesIn the context of an output statement, the << operator is referred to as the stream insertionoperator. When this program executes, the value to the operator’s right, the right operand,is inserted in the output stream. Notice that the operator points in the direction of wherethe data goes. A string literal’s characters normally print exactly as they appear between thedouble quotes. However, the characters \n are not printed on the screen (Fig. 2.1). Thebackslash (\) is called an escape character. It indicates that a “special” character is to beoutput. When a backslash is encountered in a string of characters, the next character iscombined with the backslash to form an escape sequence. The escape sequence \n meansnewline. It causes the screen cursor to move to the beginning of the next line on the screen.Some common escape sequences are listed in Fig. 2.2.
Good Programming Practice 2.1Indent the body of each function one level within the braces that delimit the function’sbody. This makes a program’s functional structure stand out and makes the program easierto read.
Good Programming Practice 2.2Set a convention for the size of indent you prefer, then apply it uniformly. The tab keymay be used to create indents, but tab stops may vary. We prefer three spaces per level ofindent.
2.3 Modifying Our First C++ Program 23
The return StatementLine 10
is one of several means we’ll use to exit a function. When the return statement is used atthe end of main, as shown here, the value 0 indicates that the program has terminated suc-cessfully. The right brace, }, (line 11) indicates the end of function main. According to theC++ standard, if program execution reaches the end of main without encountering a re-turn statement, it’s assumed that the program terminated successfully—exactly as whenthe last statement in main is a return statement with the value 0. For that reason, we omitthe return statement at the end of main in subsequent programs.
2.3 Modifying Our First C++ ProgramWe now present two examples that modify the program of Fig. 2.1 to print text on one lineby using multiple statements and to print text on several lines by using a single statement.
Printing a Single Line of Text with Multiple StatementsWelcome to C++! can be printed several ways. For example, Fig. 2.3 performs stream inser-tion in multiple statements (lines 8–9), yet produces the same output as the program ofFig. 2.1. [Note: From this point forward, we use a light gray background to highlight thekey features each program introduces.] Each stream insertion resumes printing where theprevious one stopped. The first stream insertion (line 8) prints Welcome followed by aspace, and because this string did not end with \n, the second stream insertion (line 9) be-gins printing on the same line immediately following the space.
Escapesequence Description
\n Newline. Position the screen cursor to the beginning of the next line.\t Horizontal tab. Move the screen cursor to the next tab stop.\r Carriage return. Position the screen cursor to the beginning of the
current line; do not advance to the next line.\a Alert. Sound the system bell.\\ Backslash. Used to print a backslash character.\' Single quote. Used to print a single quote character.\" Double quote. Used to print a double quote character.
Fig. 2.2 | Escape sequences.
return 0; // indicate that program ended successfully
1 // Fig. 2.3: fig02_03.cpp2 // Printing a line of text with multiple statements.3 #include <iostream> // allows program to output data to the screen4
Fig. 2.3 | Printing a line of text with multiple statements. (Part 1 of 2.)
24 Chapter 2 Introduction to C++ Programming, Input/Output and Operators
Printing Multiple Lines of Text with a Single StatementA single statement can print multiple lines by using newline characters, as in line 8 ofFig. 2.4. Each time the \n (newline) escape sequence is encountered in the output stream,the screen cursor is positioned to the beginning of the next line. To get a blank line in youroutput, place two newline characters back to back, as in line 8.
2.4 Another C++ Program: Adding IntegersOur next program obtains two integers typed by a user at the keyboard, computes the sumof these values and outputs the result using std::cout. Figure 2.5 shows the program andsample inputs and outputs. In the sample execution, we highlight the user’s input in bold.The program begins execution with function main (line 6). The left brace (line 7) beginsmain’s body and the corresponding right brace (line 22) ends it.
5 // function main begins program execution6 int main()7 {89
10 } // end function main
Welcome to C++!
1 // Fig. 2.4: fig02_04.cpp2 // Printing multiple lines of text with a single statement.3 #include <iostream> // allows program to output data to the screen45 // function main begins program execution6 int main()7 {8 std::cout << "Welcome to C++!\n";9 } // end function main
Welcometo
C++!
Fig. 2.4 | Printing multiple lines of text with a single statement.
1 // Fig. 2.5: fig02_05.cpp2 // Addition program that displays the sum of two integers.3 #include <iostream> // allows program to perform input and output
Fig. 2.5 | Addition program that displays the sum of two integers. (Part 1 of 2.)
Fig. 2.3 | Printing a line of text with multiple statements. (Part 2 of 2.)
std::cout << "Welcome ";std::cout << "to C++!\n";
\n \n\n
2.4 Another C++ Program: Adding Integers 25
Variable DeclarationsLines 9–11
are declarations. The identifiers number1, number2 and sum are the names of variables.These declarations specify that the variables number1, number2 and sum are data of typeint, meaning that these variables will hold integer values. The declarations also initializeeach of these variables to 0.
All variables must be declared with a name and a data type before they can be used in aprogram. Several variables of the same type may be declared in one declaration or in mul-tiple declarations. We could have declared all three variables in one declaration by using acomma-separated list as follows:
This makes the program less readable and prevents us from providing comments that de-scribe each variable’s purpose.
45 // function main begins program execution6 int main()7 {8 // variable declarations9
10111213 std::cout << "Enter first integer: "; // prompt user for data141516 std::cout << "Enter second integer: "; // prompt user for data1718192021 std::cout << "Sum is " << sum << ; // display sum; end line22 } // end function main
Enter first integer: 45Enter second integer: 72Sum is 117
int number1 = 0; // first integer to add (initialized to 0)int number2 = 0; // second integer to add (initialized to 0)int sum = 0; // sum of number1 and number2 (initialized to 0)
Error-Prevention Tip 2.1Although it’s not always necessary to initialize every variable explicitly, doing so will helpyou avoid many kinds of problems.
int number1 = 0, number2 = 0, sum = 0;
Fig. 2.5 | Addition program that displays the sum of two integers. (Part 2 of 2.)
int number1 = 0; // first integer to add (initialized to 0)int number2 = 0; // second integer to add (initialized to 0)int sum = 0; // sum of number1 and number2 (initialized to 0)
std::cin >> number1; // read first integer from user into number1
std::cin >> number2; // read second integer from user into number2
sum = number1 + number2; // add the numbers; store result in sum
std::endl
26 Chapter 2 Introduction to C++ Programming, Input/Output and Operators
Fundamental TypesWe’ll soon discuss the type double for specifying real numbers, and the type char for spec-ifying character data. Real numbers are numbers with decimal points, such as 3.4, 0.0 and–11.19. A char variable may hold only a single lowercase letter, a single uppercase letter,a single digit or a single special character (e.g., $ or *). Types such as int, double and charare called fundamental types. Fundamental-type names consist of one or more keywordsand therefore must appear in all lowercase letters. Appendix C contains the complete listof fundamental types.
IdentifiersA variable name (such as number1) is any valid identifier that is not a keyword. An identi-fier is a series of characters consisting of letters, digits and underscores ( _ ) that does notbegin with a digit. C++ is case sensitive—uppercase and lowercase letters are different, soa1 and A1 are different identifiers.
Placement of Variable DeclarationsDeclarations of variables can be placed almost anywhere in a program, but they must ap-pear before their corresponding variables are used in the program. For example, in the pro-gram of Fig. 2.5, the declaration in line 9
could have been placed immediately before line 14
Good Programming Practice 2.3Declare only one variable in each declaration and provide a comment that explains thevariable’s purpose in the program.
Portability Tip 2.1C++ allows identifiers of any length, but your C++ implementation may restrict identifierlengths. Use identifiers of 31 characters or fewer to ensure portability.
Good Programming Practice 2.4Choosing meaningful identifiers makes a program self-documenting—a person can un-derstand the program simply by reading it rather than having to refer to program com-ments or documentation.
Good Programming Practice 2.5Avoid using abbreviations in identifiers. This improves program readability.
Good Programming Practice 2.6Do not use identifiers that begin with underscores and double underscores, because C++compilers may use names like that for their own purposes internally. This will prevent thenames you choose from being confused with names the compilers choose.
int number1 = 0; // first integer to add (initialized to 0)
std::cin >> number1; // read first integer from user into number1
2.4 Another C++ Program: Adding Integers 27
Obtaining the First Value from the UserLine 13
displays Enter first integer: followed by a space. This message is called a prompt be-cause it directs the user to take a specific action. We like to pronounce the preceding state-ment as “std::cout gets the string "Enter first integer: ".” Line 14
uses the standard input stream object cin (of namespace std) and the stream extractionoperator, >>, to obtain a value from the keyboard. Using the stream extraction operatorwith std::cin takes character input from the standard input stream, which is usually thekeyboard. We like to pronounce the preceding statement as, “std::cin gives a value tonumber1” or simply “std::cin gives number1.”
When the computer executes the preceding statement, it waits for the user to enter avalue for variable number1. The user responds by typing an integer (as characters), thenpressing the Enter key (sometimes called the Return key) to send the characters to the com-puter. The computer converts the character representation of the number to an integerand assigns (i.e., copies) this number (or value) to the variable number1. Any subsequentreferences to number1 in this program will use this same value.
The std::cout and std::cin stream objects facilitate interaction between the userand the computer.
Users can, of course, enter invalid data from the keyboard. For example, when yourprogram is expecting the user to enter an integer, the user could enter alphabetic charac-ters, special symbols (like # or @) or a number with a decimal point (like 73.5), amongothers. In these early programs, we assume that the user enters valid data. As you progressthrough the book, you’ll learn various techniques for dealing with the broad range of pos-sible data-entry problems.
Obtaining the Second Value from the UserLine 16
prints Enter second integer: on the screen, prompting the user to take action. Line 17
obtains a value for variable number2 from the user.
Calculating the Sum of the Values Input by the UserThe assignment statement in line 19
adds the values of variables number1 and number2 and assigns the result to variable sum us-ing the assignment operator =. We like to read this statement as, “sum gets the value ofnumber1 + number2.” Most calculations are performed in assignment statements. The = op-erator and the + operator are binary operators—each has two operands. In the case of the+ operator, the two operands are number1 and number2. In the case of the preceding = op-erator, the two operands are sum and the value of the expression number1 + number2.
std::cout << "Enter first integer: "; // prompt user for data
std::cin >> number1; // read first integer from user into number1
std::cout << "Enter second integer: "; // prompt user for data
std::cin >> number2; // read second integer from user into number2
sum = number1 + number2; // add the numbers; store result in sum
28 Chapter 2 Introduction to C++ Programming, Input/Output and Operators
Displaying the ResultLine 21
displays the character string Sum is followed by the numerical value of variable sum fol-lowed by std::endl—a stream manipulator. The name endl is an abbreviation for “endline” and belongs to namespace std. The std::endl stream manipulator outputs a new-line, then “flushes the output buffer.” This simply means that, on some systems where out-puts accumulate in the machine until there are enough to “make it worthwhile” to displaythem on the screen, std::endl forces any accumulated outputs to be displayed at that mo-ment. This can be important when the outputs are prompting the user for an action, suchas entering data.
The preceding statement outputs multiple values of different types. The stream inser-tion operator “knows” how to output each type of data. Using multiple stream insertionoperators (<<) in a single statement is referred to as concatenating, chaining or cascadingstream insertion operations.
Calculations can also be performed in output statements. We could have combinedthe statements in lines 19 and 21 into the statement
thus eliminating the need for the variable sum.A powerful feature of C++ is that you can create your own data types called classes (we
introduce this capability in Chapter 3 and explore it in depth in Chapter 9). You can then“teach” C++ how to input and output values of these new data types using the >> and <<operators (this is called operator overloading—a topic we explore in Chapter 10).
2.5 ArithmeticMost programs perform arithmetic calculations. Figure 2.6 summarizes the C++ arithmeticoperators. The asterisk (*) indicates multiplication and the percent sign (%) is the modulusoperator that will be discussed shortly. The arithmetic operators in Fig. 2.6 are all binary op-erators, i.e., operators that take two operands. For example, the expression number1 +
number2 contains the binary operator + and the two operands number1 and number2.Integer division (i.e., where both the numerator and the denominator are integers)
yields an integer quotient; for example, the expression 7 / 4 evaluates to 1 and the expression17 / 5 evaluates to 3. Any fractional part in integer division is truncated —no rounding occurs.
C++ provides the modulus operator, %, that yields the remainder after integer division.The modulus operator can be used only with integer operands. The expression x % y yieldsthe remainder after x is divided by y. Thus, 7 % 4 yields 3 and 17 % 5 yields 2. In later chap-ters, we discuss many interesting applications of the modulus operator, such as determiningwhether one number is a multiple of another (a special case of this is determining whethera number is odd or even).
Good Programming Practice 2.7Place spaces on either side of a binary operator. This makes the operator stand out andmakes the program more readable.
std::cout << "Sum is " << sum << std::endl; // display sum; endline
Arithmetic Expressions in Straight-Line FormArithmetic expressions in C++ must be entered into the computer in straight-line form.Thus, expressions such as “a divided by b” must be written as a / b, so that all constants,variables and operators appear in a straight line. The algebraic notation
is generally not acceptable to compilers, although some special-purpose software packagesdo support more natural notation for complex mathematical expressions.
Parentheses for Grouping SubexpressionsParentheses are used in C++ expressions in the same manner as in algebraic expressions.For example, to multiply a times the quantity b + c we write a * ( b + c ).
Rules of Operator PrecedenceC++ applies the operators in arithmetic expressions in a precise order determined by thefollowing rules of operator precedence, which are generally the same as those in algebra:
1. Operators in expressions contained within pairs of parentheses are evaluated first.Parentheses are at the highest level of precedence. In cases of nested, or embed-ded, parentheses, such as
the operators in the innermost pair of parentheses are applied first.
2. Multiplication, division and modulus operations are applied next. If an ex-pression contains several multiplication, division and modulus operations, oper-ators are applied from left to right. Multiplication, division and modulus are onthe same level of precedence.
3. Addition and subtraction operations are applied last. If an expression containsseveral addition and subtraction operations, operators are applied from left toright. Addition and subtraction also have the same level of precedence.
The rules of operator precedence define the order in which C++ applies operators.When we say that certain operators are applied from left to right, we are referring to theassociativity of the operators. For example, the addition operators (+) in the expression
C++ operationC++ arithmeticoperator
Algebraicexpression
C++expression
Addition + f + 7 f + 7
Subtraction - p – c p - c
Multiplication * bm or b ⋅ m b * m
Division / x / y or or x ÷ y x / y
Modulus % r mod s r % s
Fig. 2.6 | Arithmetic operators.
xy--
ab--
( a * ( b + c ) )
a + b + c
30 Chapter 2 Introduction to C++ Programming, Input/Output and Operators
associate from left to right, so a + b is calculated first, then c is added to that sum to deter-mine the whole expression’s value. We’ll see that some operators associate from right to left.Figure 2.7 summarizes these rules of operator precedence. We expand this table as we in-troduce additional C++ operators. Appendix A contains the complete precedence chart.
Sample Algebraic and C++ ExpressionsNow consider several expressions in light of the rules of operator precedence. Each exam-ple lists an algebraic expression and its C++ equivalent. The following is an example of anarithmetic mean (average) of five terms:
The parentheses are required because division has higher precedence than addition. Theentire quantity ( a + b + c + d + e ) is to be divided by 5.
The following is an example of the equation of a straight line:
No parentheses are required. The multiplication is applied first because multiplication hasa higher precedence than addition.
The following example contains modulus (%), multiplication, division, addition, sub-traction and assignment operations:
The circled numbers indicate the order in which C++ applies the operators. The multiplica-tion, modulus and division are evaluated first in left-to-right order (i.e., they associate from
Operator(s) Operation(s) Order of evaluation (precedence)
( ) Parentheses Evaluated first. If the parentheses are nested, such as in the expres-sion a * ( b + c / d + e ) ), the expression in the innermost pair isevaluated first. [Caution: If you have an expression such as (a + b) *(c - d) in which two sets of parentheses are not nested, but appear“on the same level,” the C++ Standard does not specify the order inwhich these parenthesized subexpressions will be evaluated.]
*
/
%
MultiplicationDivisionModulus
Evaluated second. If there are several, they’re evaluated left to right.
+
-
AdditionSubtraction
Evaluated last. If there are several, they’re evaluated left to right.
Fig. 2.7 | Precedence of arithmetic operators.
Algebra:
C++: m = ( a + b + c + d + e ) / 5;
Algebra:
C++: y = m * x + b;
ma b c d e+ + + +
5-------------------------------------=
y mx b+=
z
6 1 2 4 3 5
= p * r % q + w / x - y;
z = pr%q + w/x – yAlgebra:
C++:
2.5 Arithmetic 31
left to right) because they have higher precedence than addition and subtraction. The additionand subtraction are applied next. These are also applied left to right. The assignment opera-tor is applied last because its precedence is lower than that of any of the arithmetic operators.
Evaluation of a Second-Degree PolynomialTo develop a better understanding of the rules of operator precedence, consider the eval-uation of a second-degree polynomial y = ax 2 + bx + c:
The circled numbers indicate the order in which C++ applies the operators. There is no arith-metic operator for exponentiation in C++, so we’ve represented x2 as x * x. In Chapter 5, we’lldiscuss the standard library function pow (“power”) that performs exponentiation.
Suppose variables a, b, c and x in the preceding second-degree polynomial are initial-ized as follows: a = 2, b = 3, c = 7 and x = 5. Figure 2.8 illustrates the order in which theoperators are applied and the final value of the expression.
Redundant ParenthesesAs in algebra, it’s acceptable to place unnecessary parentheses in an expression to make theexpression clearer. These are called redundant parentheses. For example, the preceding as-signment statement could be parenthesized as follows:
Fig. 2.8 | Order in which a second-degree polynomial is evaluated.
y = ( a * x * x ) + ( b * x ) + c;
6 1 2 4 3 5
y = a * x * x + b * x + c;
(Leftmost multiplication)
(Leftmost multiplication)
(Multiplication before addition)
(Leftmost addition)
(Last addition)
(Last operation—place 72 in y)
Step 1. y = 2 * 5 * 5 + 3 * 5 + 7;
2 * 5 is 10
Step 2. y = 10 * 5 + 3 * 5 + 7;
10 * 5 is 50
Step 3. y = 50 + 3 * 5 + 7;
3 * 5 is 15
Step 4. y = 50 + 15 + 7;
50 + 15 is 65
Step 5. y = 65 + 7;
65 + 7 is 72
Step 6. y = 72
32 Chapter 2 Introduction to C++ Programming, Input/Output and Operators
2.6 Decision Making: Equality and Relational OperatorsWe now introduce a simple version of C++’s if statement that allows a program to takealternative action based on whether a condition is true or false. If the condition is true, thestatement in the body of the if statement is executed. If the condition is false, the bodystatement is not executed. We’ll see an example shortly.
Conditions in if statements can be formed by using the relational operators andequality operators summarized in Fig. 2.9. The relational operators all have the same levelof precedence and associate left to right. The equality operators both have the same level ofprecedence, which is lower than that of the relational operators, and associate left to right.
Using the if StatementThe following example (Fig. 2.10) uses six if statements to compare two numbers inputby the user. If the condition in any of these if statements is satisfied, the output statementassociated with that if statement is executed.
Algebraic relationalor equality operator
C++ relational orequality operator
SampleC++condition Meaning of C++ condition
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
≥ >= x >= y x is greater than or equal to y
≤ <= x <= y x is less than or equal to y
Equality operators
= == x == y x is equal to y
≠ != x != y x is not equal to y
Fig. 2.9 | Relational and equality operators.
Common Programming Error 2.2Reversing the order of the pair of symbols in the operators !=, >= and <= (by writing themas =!, => and =<, respectively) is normally a syntax error. In some cases, writing != as =!will not be a syntax error, but almost certainly will be a logic error that has an effect atexecution time. You’ll understand why when you learn about logical operators inChapter 5. A fatal logic error causes a program to fail and terminate prematurely. Anonfatal logic error allows a program to continue executing, but usually produces incor-rect results.
Common Programming Error 2.3Confusing the equality operator == with the assignment operator = results in logic errors.We like to read the equality operator as “is equal to” or “double equals,” and the assign-ment operator as “gets” or “gets the value of” or “is assigned the value of.” As you’ll see inSection 5.9, confusing these operators may not necessarily cause an easy-to-recognize syn-tax error, but may cause subtle logic errors.
2.6 Decision Making: Equality and Relational Operators 33
1 // Fig. 2.13: fig02_13.cpp2 // Comparing integers using if statements, relational operators3 // and equality operators.4 #include <iostream> // allows program to perform input and output56789
10 // function main begins program execution11 int main()12 {13 int number1 = 0; // first integer to compare (initialized to 0)14 int number2 = 0; // second integer to compare (initialized to 0)1516 cout << "Enter two integers to compare: "; // prompt user for data171819202122 if ( )23 cout << number1 << " != " << number2 << endl;2425 if ( )26 cout << number1 << " < " << number2 << endl;2728 if ( )29 cout << number1 << " > " << number2 << endl;3031 if ( )32 cout << number1 << " <= " << number2 << endl;3334 if ( )35 cout << number1 << " >= " << number2 << endl;36 } // end function main
Enter two integers to compare: 3 73 != 73 < 73 <= 7
Enter two integers to compare: 22 1222 != 1222 > 1222 >= 12
Enter two integers to compare: 7 77 == 77 <= 77 >= 7
Fig. 2.10 | Comparing integers using if statements, relational operators and equality operators.
using std::cout; // program uses coutusing std::cin; // program uses cinusing std::endl; // program uses endl
cin >> number1 >> number2; // read two integers from user
34 Chapter 2 Introduction to C++ Programming, Input/Output and Operators
using DeclarationsLines 6–8
are using declarations that eliminate the need to repeat the std:: prefix as we did in ear-lier programs. We can now write cout instead of std::cout, cin instead of std::cin andendl instead of std::endl, respectively, in the remainder of the program.
In place of lines 6–8, many programmers prefer to provide the using directive
which enables a program to use all the names in any standard C++ header (such as<iostream>) that a program might include. From this point forward in the book, we’ll usethe preceding directive in our programs. In Chapter 21, Other Topics, we’ll discuss someissues with using directives in large-scale systems.
Variable Declarations and Reading the Inputs from the UserLines 13–14
declare the variables used in the program and initializes them to 0.The program uses cascaded stream extraction operations (line 17) to input two inte-
gers. Remember that we’re allowed to write cin (instead of std::cin) because of line 7.First a value is read into variable number1, then a value is read into variable number2.
Comparing NumbersThe if statement in lines 19–20
compares the values of variables number1 and number2 to test for equality. If the values areequal, the statement in line 20 displays a line of text indicating that the numbers are equal.If the conditions are true in one or more of the if statements starting in lines 22, 25, 28,31 and 34, the corresponding body statement displays an appropriate line of text.
Each if statement in Fig. 2.10 has a single statement in its body and each body state-ment is indented. In Chapter 4 we show how to specify if statements with multiple-state-ment bodies (by enclosing the body statements in a pair of braces, { }, creating what’scalled a compound statement or a block).
using std::cout; // program uses coutusing std::cin; // program uses cinusing std::endl; // program uses endl
using namespace std;
int number1 = 0; // first integer to compare (initialized to 0)int number2 = 0; // second integer to compare (initialized to 0)
Common Programming Error 2.4Placing a semicolon immediately after the right parenthesis after the condition in an if
statement is often a logic error (although not a syntax error). The semicolon causes the bodyof the if statement to be empty, so the if statement performs no action, regardless ofwhether or not its condition is true. Worse yet, the original body statement of the if state-ment now becomes a statement in sequence with the if statement and always executes,often causing the program to produce incorrect results.
2.7 Wrap-Up 35
White SpaceRecall that whitespace characters, such as tabs, newlines and spaces, are normally ignoredby the compiler. So, statements may be split over several lines and may be spaced accordingto your preferences. It’s a syntax error to split identifiers, strings (such as "hello") andconstants (such as the number 1000) over several lines.
Operator PrecedenceFigure 2.11 shows the precedence and associativity of the operators introduced in thischapter. The operators are shown top to bottom in decreasing order of precedence. Allthese operators, with the exception of the assignment operator =, associate from left toright. Addition is left-associative, so an expression like x + y + z is evaluated as if it hadbeen written (x + y) + z. The assignment operator = associates from right to left, so an ex-pression such as x = y = 0 is evaluated as if it had been written x = (y = 0), which, as we’llsoon see, first assigns 0 to y, then assigns the result of that assignment—0—to x.
2.7 Wrap-UpYou learned many important basic features of C++ in this chapter, including displayingdata on the screen, inputting data from the keyboard and declaring variables of fundamen-
Good Programming Practice 2.8A lengthy statement may be spread over several lines. If a single statement must be splitacross lines, choose meaningful breaking points, such as after a comma in a comma-sepa-rated list, or after an operator in a lengthy expression. If a statement is split across two ormore lines, indent all subsequent lines and left-align the group of indented lines.
Operators Associativity Type
() [See caution in Fig. 2.7] grouping parentheses* / % left to right multiplicative+ - left to right additive<< >> left to right stream insertion/extraction< <= > >= left to right relational== != left to right equality= right to left assignment
Fig. 2.11 | Precedence and associativity of the operators discussed so far.
Good Programming Practice 2.9Refer to the operator precedence and associativity chart (Appendix A) when writing ex-pressions containing many operators. Confirm that the operators in the expression are per-formed in the order you expect. If you’re uncertain about the order of evaluation in acomplex expression, break the expression into smaller statements or use parentheses to forcethe order of evaluation, exactly as you’d do in an algebraic expression. Be sure to observethat some operators such as assignment (=) associate right to left rather than left to right.
36 Chapter 2 Introduction to C++ Programming, Input/Output and Operators
tal types. In particular, you learned to use the output stream object cout and the inputstream object cin to build simple interactive programs. We explained how variables arestored in and retrieved from memory. You also learned how to use arithmetic operators toperform calculations. We discussed the order in which C++ applies operators (i.e., therules of operator precedence), as well as the associativity of the operators. You also learnedhow C++’s if statement allows a program to make decisions. Finally, we introduced theequality and relational operators, which you use to form conditions in if statements.
The non-object-oriented applications presented here introduced you to basic pro-gramming concepts. As you’ll see in Chapter 3, C++ applications typically contain just afew lines of code in function main—these statements normally create the objects that per-form the work of the application, then the objects “take over from there.” In Chapter 3,you’ll learn how to implement your own classes and use objects of those classes in appli-cations.
672.* and ->* operators 670'\0', null character 253'\n', newline character 252[] (operator for map) 507* (multiplication operator) 29* (pointer dereference or indirection op-
signment operator) 629| (bitwise inclusive OR operator) 621,
669|= (bitwise inclusive OR assignment op-
erator) 515, 629, 669|| (logical OR operator) 123, 124, 668
truth table 124|| logical OR operator 181~ (bitwise complement operator) 621,
669
Numerics0X 4320x 4322-D array 211
Aabbreviating assignment expressions 95abort 797abort function 272, 574absolute value 131abstract base class 390, 391, 738abstract class 390, 391, 392, 407abstract operation in the UML 734access a global variable 169access function 265
access non-static class data membersand member functions 301
access private member of a class 47access privileges 241, 243access specifier 39, 47, 291, 726
private 47protected 258public 47
access the caller’s data 164access violation 476accessor 49Account class (ATM case study) 690,
accounts-receivable system 446accumulate algorithm 529, 532, 553,
555, 559accumulated outputs 28action 74, 75action expression 71action expression in the UML 705action of an object 704action state 71action state in the UML 705action state symbol 71activation in a UML sequence diagram
720activation record 159activity diagram 70, 71, 78, 105
activity in the UML 690, 703, 707activity of a portion of a software system
71actor in use case in the UML 689adapter 509add a new account to a file 472add an integer to a pointer 247addition 29addition assignment operator (+=) 95addition program that displays the sum of
two numbers 24address of a bit field 633address operator (&) 231, 232, 234, 308,
672addressable storage unit 633adjacent_difference algorithm 559adjacent_find algorithm 558aggregation 264, 696aiming a derived-class pointer at a base-
alignment 617all 514all_of algorithm 533, 536, 558allocate 321allocate dynamic memory 575allocate memory 140, 321allocator 493allocator_type 479alphabetizing strings 643alter the flow of control 121ambiguity problem 672, 677American National Standards Institute
(ANSI) 2American Standard Code for Information
Interchange (ASCII) 116analysis stage of the software life cycle 688analyzing a project’s requirements 683and operator keyword 668and_eq operator keyword 669“ANDed” 623Android 16
operating system 16smartphone 16
angle brackets (< and >) 173, 791angle brackets (< and >) in templates 583anonymous function objects 518ANSI (American National Standards In-
stitute) 2ANSI/ISO 9899: 1990 2any 514any_of algorithm 533, 536, 558Apache Software Foundation 15append 595append data to a file 447, 448Apple Inc. 16Apple Macintosh 16argument coercion 138argument for a macro 792argument to a function 41arguments in correct order 136arguments passed to member-object con-
structors 283arithmetic assignment operators 95, 96arithmetic calculations 28arithmetic mean 30arithmetic operator 28arithmetic overflow 84, 570arithmetic overflow error 579arithmetic underflow error 579“arity” of an operator 309<array> header 140array
built-in 229, 238name 250notation for accessing elements 251subscripting 251
array 187bounds checking 198
Array class 324Array class definition with overloaded
operators 328Array class member-function and
friend function definitions 329array class template 186Array class test program 324array subscript operator ([]) 328arrow 71
arrow member selection operator (->)265
arrow operator (->) 293arrowhead in a UML sequence diagram
720ASCII (American Standard Code for In-
formation Interchange)Character Set 116, 252, 422
assert 797assign member function of class
string 593assign member function of list 498assign one iterator to another 484assigning addresses of base-class and de-
rived-class objects to base-class and de-rived-class pointers 378
96assignment statement 27, 97associate from left to right 35, 98associate from right to left 35, 98, 116association 508association (in the UML) 694, 695, 696,
banking system 456bar chart 193, 194bar chart printing program 194bar of asterisks 193, 194base 2 621base case(s) 175, 179, 182base class 343, 345, 733base-class catch 578base-class constructor 370base-class exception 578base-class member accessibility in derived
class 371base-class pointer to a derived-class object
389base-class private member 361base-class subobject 678base e 132
base specified for a stream 436base-10 number system 132, 432base-16 number system 432base-8 number system 432base-class initializer syntax 359base-class member function redefined in a
derived class 368BasePlusCommissionEmployee class
header 402BasePlusCommissionEmployee class
implementation file 402BasePlusCommissionEmployee class
represents an employee who receives abase salary in addition to a commis-sion 352
BasePlusCommissionEmployee classtest program 355
BasePlusCommissionEmployee classthat inherits from class Commission-Employee, which does not provideprotected data 367
basic searching and sorting algorithms ofthe Standard Library 533
basic_fstream class template 420, 446basic_ifstream class template 420,
445basic_ios class template 418, 677basic_iostream class template 418,
420, 446, 677basic_istream class template 418,
446, 677basic_istringstream class template
609basic_ofstream class template 446basic_ostream class template 420,
446, 677basic_ostringstream class template
609basic_string class template 592begin function 240begin iterator 608beginmember function of class string
608begin member function of containers
479begin member function of first-class
containers 480beginning of a file 452beginning of a stream 452behavior 707
of a class 4behavior of the system 703, 704, 707, 716bell 23Bell Laboratories 2bidirectional iterator 482, 483, 494, 501,
504, 505, 518, 540, 541, 542bidirectional iterator operations 484bidirectional navigability in the UML
727binary (base 2) number system 781binary arithmetic operator 90binary function 553binary function object 553binary number 634binary number system 650binary operator 27, 28binary predicate function 497, 523, 532,
536, 540, 545, 550
binary_search algorithm 209, 533,536, 558
bit 616bit field 621, 630, 633bit-field manipulation 633bit-field member of structure 631bit fields save space 633bit manipulation 621bitand operator keyword 669bitor operator keyword 669“bits-and-bytes” level 621bitset 477, 513, 514, 515<bitset> header 140bitwise AND assignment 669bitwise AND assignment operator (&=)
629bitwise AND operator (&) 621, 621, 624,
626bitwise AND, bitwise inclusive-OR, bit-
wise exclusive-OR and bitwise com-plement operators 624
624, 627, 629, 788bitwise exclusive OR 669bitwise exclusive OR assignment operator
(^=) 629bitwise exclusive OR operator (^) 621,
624, 627bitwise inclusive OR 669bitwise inclusive OR assignment operator
(|=) 629bitwise inclusive OR operator (|) 461,
621, 624, 626bitwise left-shift operator (<<) 304, 627bitwise logical OR 515bitwise operator keywords 669bitwise operators 621, 622, 629bitwise right-shift operator (>>) 304bitwise shift operator 627BlackBerry OS 15block 34, 44, 66, 77, 89, 153, 155, 156block is active 153block is exited 153block of data 655block of memory 498, 655block scope 155, 265
variable 265body of a class definition 39body of a function 21, 22, 40body of a loop 102, 105Booch, Grady 684bool data type 74bool value false 74bool value true 74boolalpha stream manipulator 125,
432, 438Boolean attribute in the UML 699Boost C++ Libraries 17boundary of a storage unit 633bounds checking 198braces ({}) 22, 34, 66, 77, 89, 117braces in a do…while statement 112bracket ([]) 187break statement 118, 121
802 Index
break statement exiting a for statement121
brittle software 364buffer is filled 420buffer is flushed 420buffer overflow 198buffered output 420buffered standard error stream 418buffering 443building-block approach 3built-in array 229, 238business-critical computing 565byte 621
C.C extension 6C legacy code 791, 792, 797C-like pointer-based array 477C string 252c_str member function of class string
607C++ 2C++ compiler 7C++ development environment 7, 8C++ preprocessor 7, 21C++ Standard Library 3
C++11 17, 178all_of algorithm 536anonymous function objects 518any_of algorithm 536associative container keys are immu-
table 477auto keyword 213, 503begin function 240, 489cbegin container member function
489cend container member function
489compiler fix for types ending in >>
502copy_n algorithm 541crbegin container member func-
tion 490crend container member function
490default type arguments for function
template type parameters 589delegating constructor 271end function 240, 489find_if_not algorithm 537forward_list class template 476,
494in-class initializer 120, 260insert container member function
(now returns an iterator) 493,494
iota algorithm 559is_heap algorithm 551is_heap_until algorithm 551list initialization 94, 507list initialization of a return type 507list initialization of associative con-
stod function 612stof function 612stoi function 612stol function 612stold function 612stoll function 612stoul function 612stoull function 612to_string function 612trailing return types for functions
175unique_ptr class template 575,
575, 578unordered_multimap class tem-
plate 477unordered_multiset class tem-
plate 477unordered_set class template 477
calculations 28, 70call a function 41call stack 242calling function (caller) 40, 47calling functions by reference 233camel case 39capacity member function
of string 601of vector 488
capacity of a string 599Card Shuffling and Dealing
cast operator 85, 90, 139, 337, 338cast operator function 337cast variable visible in debugger 792catch a base class object 578catch all exceptions 579catch block 226catch clause (or handler) 566, 570catch handler 564catch related errors 572catch(...) 579cbegin member function of containers
479cbeginmember function of vector 489<cctype> header 140, 634CD 445ceil function 131cend member function of containers 479cend member function of vector 489cerr (standard error stream) 9, 66, 418,
cin.clear 442cin.eof 422, 442cin.get function 115, 116, 423cin.tie function 443circular include 730class 4, 701, 707, 711, 726, 792
attribute 45client-code programmer 62constructor 50data member 5, 45default constructor 51, 53define a constructor 52define a member function 38implementation programmer 62instance of 46interface 58interface described by function pro-
totypes 58member function 38member-function implementations
in a separate source-code file 59
Index 803
class (cont.)name 728naming convention 39object of 46public services 58services 49
class average on a quiz 79class average problem 79class definition 39class development 324class diagram
for the ATM system model 697, 722in the UML 690, 693, 696, 698,
701, 708, 726, 729, 735, 736,737
class diagram (UML) 41class hierarchy 344, 389, 391class-implementation programmer 62class keyword 173, 583class libraries 109class library 372class members default to private access
classic stream libraries 417clear function of ios_base 442clear member function of containers
479clear member function of first-class
containers 494client code 376client-code programmer 62client of a class 707, 717client of an object 48<climits> header 141clog (standard error buffered) 418, 419,
collaboration 714, 715, 717collaboration diagram in the UML 691,
716collaboration in the UML 714colon (:) 155, 286, 675column 211column headings 189column subscript 211comma operator (,) 104, 181comma-separated list
of parameters 13625, 35, 104, 230command-line argument 240comma-separated list of base classes 675comment 20CommissionEmployee class header 399CommissionEmployee class implemen-
tation file 400CommissionEmployee class represents
an employee paid a percentage of grosssales 347
CommissionEmployee class test pro-gram 350
CommissionEmployee class uses mem-ber functions to manipulate its pri-vate data 365
Common Programming Errors overviewxxiii
communication diagram in the UML691, 716, 717
commutative 336commutative operation 336comparator function object 501, 505comparator function object less 501,
512compare iterators 484compare member function of class
string 597comparing
strings 639, 642comparing blocks of memory 655comparing strings 595compilation error 95compilation unit 667compile 7compiler 21, 90compiling
(=) operators 32, 127conserving memory 153consistent state 65const 281, 313, 792const keyword 163const member function 40, 281const member function on a const ob-
ject 282constmember function on a non-const
object 282const object 192, 282const object must be initialized 192const objects and const member func-
tions 282const qualifier 191, 240, 661const qualifier before type specifier in
parameter declaration 166const variables must be initialized 192const version of operator[] 335const with function parameters 240const_cast
cannot be virtual 389cannot specify a return type 50conversion 337, 339copy 332default 53default arguments 269defining 52explicit 339function prototype 59in a UML class diagram 54inherit 370inherit from base class 370naming 52parameter list 52single argument 339, 340
constructors and destructors called auto-matically 272
begin function 479cbegin function 479cend function 479clear function 479crbegin function 479crend function 479empty function 478end function 479erase function 479insert function 478max_size function 478rbegin function 479rend function 479size function 478swap function 478
continue statement 121continue statement terminating a single
iteration of a for statement 122control characters 637control statement 70, 73, 74
control variable 102control-variable name 104controlling expression 117converge on the base case 182conversion constructor 337, 339conversion operator 337
explicit 340conversions among fundamental types
by cast 337convert a binary number to decimal 786convert a hexadecimal number to decimal
786convert among user-defined types and
built-in types 337convert an octal number to decimal 786convert between types 337convert lowercase letters 140convert strings to floating-point types 612convert strings to integral types 612converting strings to C-style strings and
copy of the argument 241copy_backward algorithm 539, 558copy_if algorithm 558copy_n algorithm 541, 558copy-and-paste approach 356copying strings 640correct number of arguments 136correct order of arguments 136correctly initializing and using a constant
variable 191cos function 131cosine 131count algorithm 529, 532, 558count function of associative container
stant 797.cpp extension 6CPU (central processing unit) 8craps simulation 146, 147, 150crbegin member function of containers
479crbegin member function of vector
490create an object (instance) 40create your own data types 28CreateAndDestroy class
definition 273member-function definitions 274
creating a random access file 457Creating a random-access file with 100
blank records sequentially 461Creating a sequential file 447creating an association 508Credit inquiry program 453credit processing program 458crend member function of containers
479crend member function of vector 490<cstdio> header 141<csdtlib> header 574<cstdlib> header 140, 141, 646<cstring> header 140, 640<ctime> header 140, 146<Ctrl>-d 116, 429, 449Ctrl key 116<Ctrl>-z 116, 429, 449<cstdlib> header 142current position in a stream 452cursor 22.cxx extension 6
Ddangerous pointer manipulation 407dangling-else problem 77dangling pointer 333dangling reference 167data hiding 47, 49data member 5, 45, 46, 726data member function of class string
607data members 38data persistence 445data structures 475data types
bool 74char 116, 139double 85, 108float 85, 138int 25long 120long double 138long int 120, 139long long 120, 138long long int 138short 120short int 120unsigned 145unsigned char 139unsigned int 139, 145unsigned long 138unsigned long int 138unsigned long long 138unsigned long long int 138unsigned short 139unsigned short int 139
data types in the UML 44Date class 283, 316Date class definition 283Date class definition with overloaded in-
crement operators 316Date class member function definitions
284Date class member-function and
friend-function definitions 317Date class test program 319__DATE__ predefined symbolic constant
797date source file is compiled 797deallocate 321deallocate memory 321, 575debugger 792debugging 144debugging aid 795debugging tool 797dec stream manipulator 427, 432, 436decimal (base 10) number system 649,
650, 781decimal (base-10) number system 432decimal numbers 436, 634decimal point 85, 90, 91, 109, 421, 432decision 74decision in the UML 705decision symbol 74declaration 25declaration of a function 59declaring a static member function
const 301decrement
a pointer 247decrement a control variable 101
Index 805
decrement operator (--) 96decrement operators 315default access mode for class is private
47default argument 167, 266default arguments with constructors 266default case 117, 118, 144default constructor 51, 53, 267, 288, 316,
327, 332, 370, 478provided by the compiler 53provided by the programmer 53
default copy constructor 287default delimiter 425default memberwise assignment 279default memberwise copy 332default precision 90default to decimal 436default to public access 616default type argument for a type parame-
ter 589default type arguments for function tem-
plate type parameters 589default_random_engine 151#define 794, 796define a constructor 52define a member function of a class 38Define class GradeBook with a member
function displayMessage, create aGradeBook object, and call its dis-playMessage function 38
Define class GradeBook with a memberfunction that takes a parameter, createa GradeBook object and call its dis-playMessage function 42
323delete a record from a file 472delete operator 321, 389deleting dynamically allocated memory
333delimiter 254, 644delimiter (with default value '\n') 423delimiting characters 644Deposit class (ATM case study) 693,
696, 699, 700, 708, 715, 716, 724,727, 733, 734
DepositSlot class (ATM case study)693, 695, 699, 708, 716, 728
<deque> header 140, 499deque class template 485, 498
push_front function 499shrink_to_fit member function
490dereference
a const iterator 482a null pointer 232a pointer 232, 235, 241an iterator 480, 481, 484an iterator positioned outside its con-
tainer 490
dereferencing operator (*) 232derive one class from another 264derived class 343, 345, 372, 733, 734
indirect 401derived-class catch 578descriptive words and phrases 699, 701deserialized object 473design process 5, 683, 689, 708, 713design specification 689destructor 272, 357, 478
called in reverse order of constructors272
destructor in a derived class 370destructors called in reverse order 370Dev C++ 7diagnostics that aid program debugging
141diamond inheritance 677diamond symbol 71, 74dice game 146die rolling
using an array instead of switch195
difference_type 480digit 26, 253, 781direct base class 345directly reference a value 229disk 8, 9disk drive 417disk I/O completion 570disk space 449, 573, 574displacement 410display screen 417, 419divide by zero 9DivideByZeroException 566divides function object 554division 29do…while repetition statement 72, 110,
111dollar amount 109dot (.) operator 40dot operator (.) 265, 293, 384, 576dotted line 71double 26double data type 85, 108, 138double-ended queue 498double-precision floating-point number
89double quote 22, 23double-selection statement 72double-word boundary 617“doubly initializing” member objects 288doubly linked list 494, 477downcasting 383driver program 55dummy value 85duplicate keys 500, 505DVD 445dynamic binding 384, 406, 407, 410dynamic casting 411dynamic data structure 229dynamic memory 575dynamic memory management 321dynamic storage duration 153dynamic_cast 413, 578dynamically allocate array of integers 328dynamically allocated memory 279, 280,
333, 389, 575allocate and deallocate storage 272
dynamically allocated storage 332dynamically determine function to exe-
cute 383
EEclipse 7Eclipse Foundation 15edit 6edit a program 6editor 6element of an array 186elided UML diagram 694#elif 795emacs 6embedded parentheses 29embedded system 15Employee class 283
definition showing composition 285definition with a static data member
to track the number of Employeeobjects in memory 299
empty parentheses 40, 41, 43empty statement 78empty string 48, 601encapsulate 47encapsulation 5, 49, 262, 278, 288end function 240end line 28end member function of class string
608end member function of containers 479end member function of first-class con-
tainer 480end of a sequence 536end of a stream 452“end of data entry” 85end-of-file 116, 117, 254, 442#endif preprocessing directive 795#endif preprocessor directive 259endl 28, 90end-of-file 449end-of-file indicator 449end-of-file key combination 449end-of-file marker 445Enter key 27enter key 117, 118enum
eof member function 422, 442eofbit of stream 442equal algorithm 523, 558equal to 32equal_range algorithm 546, 548, 558equal_range function of associative
container 503equal_to function object 554equality and relational operators 33equality operator (==) 324, 480equality operators 32, 33equality operators (== and !=) 74, 123equation of straight line 30erase 603erase member function of class string
off-by-one 104error bits 425error detected in a constructor 571error state of a stream 422, 440, 441escape character 22escape early from a loop 121escape sequence 22, 24escape sequences
executable image 8executable program 7execute a program 6, 8execution-time error 9
execution-time overhead 407exit 449exit a function 23exit function 272, 273, 574EXIT_FAILURE 449EXIT_SUCCESS 449exp function 131expand a macro 793explicit constructor 339explicit conversion 90explicit keyword 52, 339
conversion operators 340exponential “explosion” of calls 182exponential complexity 182exponential function 131exponentiation 31, 108expression 74, 75, 90, 104extensibility 376extensibility of C++ 314extensible language 179extensible markup language (XML) 473extensible programming language 40extern keyword 154extern storage-class specifier 152
Ffabs function 131Facebook 15factorial 176, 177, 179fail member function 442failbit 449failbit of stream 422, 426, 442false 32false 74, 75, 182, 438fatal logic error 32fatal runtime error 9fault-tolerant programs 225, 561Fibonacci series 179, 182field width 110, 189, 426, 429fields larger than values being printed 435FIFO 477, 498FIFO (first-in, first-out) 511file 445, 451file of n bytes 445file open mode 447, 450file open modes
498fractional parts 90fragile software 364free function (global function) 262free store 321friend function 289, 346friend of a derived class 675friends are not member functions 291Friends can access private members of
class 289friendship granted, not taken 289front member function of queue 511frontmember function of sequence con-
235return a result 47signature 137, 171that takes no arguments 162trailing return type 175
function body 40function call 41function call operator () 340, 410function call stack 242function object 501, 505, 518, 553
binary 553divides 554equal_to 554
function object (cont.)greater 554greater_equal 554less 554less_equal 554logical_end 554logical_not 554logical_or 554minus 554modulus 554multiplies 554negate 554not_equal_to 554plus 554predefined in the STL 553
function object less< int > 501function object less< T > 505, 512function overhead 793function overloading 416function pointer 407, 410, 518, 553function prototype 58, 109, 289, 792
parameter names optional 59function prototype scope 155, 156function scope 155, 155function template 173, 582, 589function template specialization 173<functional> header 141, 553functional structure of a program 22functions 3functions for manipulating data in the
standard library containers 141functions with empty parameter lists 162function-template specialization 582fundamental type 26fundamental types
unsigned int 82
Ggame of chance 146game of craps 147game playing 141gcount function of istream 426general class average problem 85general utilities library <cstdlib> 797generalities 376generalization in the UML 733generalized numeric operations 557general-utilities library <cstdlib> 646generate algorithm 520, 521, 558generate_n algorithm 520, 521, 558generating values to be placed into ele-
ments of an array 191generator function 520generic algorithms 519generic programming 582get a value 49get and set functions 48get member function 422, 423get pointer 452getline function for use with class
string 593getline function of cin 424getline function of the string header
43, 48gets the value of 32global 60global function 130global identifier 665
global namespace 667global namespace scope 155, 156, 272,
298global object constructors 272global scope 272, 274, 667global variable 154, 156, 158, 169, 667golden mean 179golden ratio 179good function of ios_base 442Good Programming Practices overview
xxiiigoodbit of stream 442goto elimination 70goto statement 70GradeBook.cpp 80, 86GradeBook.h 80, 85graph information 194Graphical User Interface (GUI) 16greater function object 554greater_equal function object 554greater-than operator 32greater-than-or-equal-to operator 32guard condition 74guard condition in the UML 705GUI (Grahical User Interface) 16guillemets (« and ») in the UML 54
H.h filename extension 54half-word 617handle on an object 264hard disk 445hardcopy printer 9hardware platform 2has-a relationship 343, 695, 283header 54, 62, 139, 259, 372, 791Headers
<algorithm> 492, 558<cmath> 109<deque> 499<exception> 562<forward_list> 494<fstream> 445<functional> 553<iomanip.h> 90<iostream> 21, 116<list> 494<map> 505, 507<memory> 575<numeric> 559<queue> 511, 512<set> 501<stack> 509<stdexcept> 562, 578<string> 43<typeinfo> 413<unordered_map> 505, 507<unordered_set> 501, 504<vector> 221how they are located 57name enclosed in angle brackets (<
74, 75if…else statement activity diagram 75#ifdef preprocessing directive 795#ifndef preprocessor directive 259#ifndef preprocessing directive 795ifstream 446, 450, 451, 464ifstream constructor function 450ignore 312ignore function of istream 425implementation inheritance 393implementation of a member function
a pointer 247increment a control variable 101, 104,
105increment an iterator 484increment operator 315
increment operator (++) 96indentation 73, 76independent software vendor (ISV) 3index 186indexed access 498indirect base class 345indirect derived class 401indirection 229, 407indirection operator (*) 232, 234indirectly reference a value 229inequality 668inequality operator (!=) 324inequality operator keywords 668infinite loop 89, 104, 176information hiding 5inherit constructors 370inherit constructors from base class 370inherit interface 390inherit members of an existing class 343Inheritance
tance 393multiple 672relationships of the I/O-related class-
es 420, 446virtual base class 679
initial state 71initial state in the UML 703, 705initial value of a control variable 101, 103initial value of an attribute 702initialize a pointer 230initializer 189initializer list 189, 253initializer_list 552initializer_list class template 336initializing an array’s elements to zeros
and printing the array 189initializing multidimensional arrays 212initializing the elements of an arraywith
a declaration 190inline 164, 335, 794inline function 163inline function 792, 793inline function to calculate the volume
of a cube 164inline keyword 163inner block 155inner_product algorithm 559innermost pair of parentheses 29inplace_merge algorithm 542, 559input a line of text 424Input and output stream iterators 481input from string in memory 140input iterator 482, 484, 523, 526, 529,
532, 540, 545input line of text into an array 254input/output library functions 141input/output of objects 473input/output operations 71input/output stream header <iostream>
21input sequence 481input stream 422, 423
input stream iterator 481input stream object (cin) 27inputting from strings in memory 609insert function of associative container
503, 507insert member function of class
string 605insert member function of containers
478insert member function of sequence
container 493inserter function template 540insertion at back of vector 486instance 4instance of a class 46instant access processing 466instant-access application 456instruction 8int 21, 26, 138int & 165int operands promoted to double 90integer 21, 25integer arithmetic 304Integer class definition 575integer division 28, 90integer promotion 90integers prefixed with 0 (octal) 436integers prefixed with 0x or 0X (hexadec-
imal) 436integral constant expression 112integral size limits 141integrated development environment
(IDE) 6interaction diagram in the UML 716interactions among objects 714, 717interest rate 108interface 58Interface Builder 16interface inheritance 393interface of a class 58internal spacing 434internal stream manipulator 432, 434International Electrotechnical Commis-
sion (IEC) 2International Standards Organization
(ISO) 2invalid_argument class 578invalid_argument exception 493invalid_argument exception class 260invoking a non-const member function
on a const object 281<iomanip> header 140, 791, 418, 427<iomanip.h> header 90iOS 15ios_base base class 440ios_base class
precision function 427width member function 429
ios::app file open mode 447ios::ate file open mode 448ios::beg seek direction 452ios::binary file open mode 448, 461,
464ios::cur seek direction 452ios::end seek direction 452ios::in file open mode 448, 450ios::out file open mode 447ios::trunc file open mode 448
Llabel 155labels in a switch structure 155lambda expression 518, 556lambda function 556lambda introducer 557large object 166last-in, first-out (LIFO) 158
data structure 477, 509order 582, 587
late binding 384leading 0 436leading 0x and leading 0X 432, 436left brace ({) 21, 24left justification 110, 434left-shift operator (<<) 304, 621, 621,
627, 628left side of an assignment 128, 187, 276,
328left stream manipulator 110, 432, 433,
433left-to-right associativity 98left value 128left-shift assignment operator (<<=) 629left-shift operator (<<) 419left-to-right associativity 35left-to-right evaluation 29, 30legacy C code 792legacy code 797length member function of class
string 593length of a string 254length of a substring 340length_error exception 493, 578, 599less function object 554less_equal function object 554
live-code approach xxiiiload 6loader 8, 8local automatic object 275local variable 44, 154, 156<locale> header 141log function 132log10 function 132logarithm 132logic error 6, 32logic_error exception 578logical AND 668logical AND (&&) 123logical negation 123, 124logical NOT (!) 123, 124, 668logical operator keywords 668logical operators 123logical OR (||) 123, 124, 626, 668logical_and function object 554logical_not function object 554logical_or function object 554long data type 120long double data type 138long int 177
810 Index
long int data type 120, 139long long data type 120, 138long long int data type 138loop 72, 79loop-continuation condition 72, 101,
102, 104, 105, 110, 111loop counter 101loop-continuation condition fails 182looping statement 72loss of data 442lower_bound algorithm 548, 558lower_bound function of associative
prevent 577memory-access violation 476memset 656, 659merge algorithm 538, 540, 558merge in the UML 705merge member function of list 498merge symbol 79message in the UML 714, 716, 717, 720message passing in the UML 719Microsoft
Visual C++ 6Microsoft Visual C++ 669Microsoft Windows 116min algorithm 552, 559min_element algorithm 529, 532, 559minmax algorithm 552, 559
minmax_element algorithm 529, 532,553, 559
minus function object 554minus sign (-) indicating private visibility
in the UML 726minus sign, – (UML) 50mismatch algorithm 522, 524, 558mission-critical computing 565mixed-type expression 138model of a software system 694, 702, 735modifiable lvalue 308, 328, 335modify a constant pointer 243modify address stored in pointer variable
674, 675, 677multiple inheritance demonstration 673multiple parameters to a function 44multiple-selection statement 72, 112multiple-source-file program
compilation and linking process 62multiple-statement body 34multiplication 28, 29multiplicative operators (*, /, %) 90multiplicity 694multiplies function object 554mutable
data member 663, 663, 664demonstration 664keyword 152, 663
mutable data member 664mutating sequence algorithms 558mutator 49
Nname decoration 171name function of class type_info 413name handle 264
on an object 264name mangling 171name mangling to enable type-safe link-
age 172name of a control variable 101name of a source file 796name of a user-defined class 39name of a variable 152name of an array 187named constant 191namespace 22
alias 668global 667nested 667qualifier 668unnamed 667
Index 811
namespace 665namespace alias 668namespace keyword 665, 667namespace member 665namespace scope 155namespaces 665naming conflict 291, 665narrowing conversion 95natural logarithm 132navigability arrow in the UML 726NDEBUG 797near container 477negate function object 554nested blocks 155nested control statement 92nested for statement 194, 214, 219nested if…else statement 76, 77nested message in the UML 718nested namespace 667nested namespace 667nested parentheses 29NetBeans 7network connection 417network message arrival 570new 332new calls the constructor 321new failure handler 574<new> header 572new operator 321new returning 0 on failure 573new stream manipulators 430new throwing bad_alloc on failure 572,
573newline ('\n') escape sequence 22, 28,
35, 118, 252, 421, 637next_permutation algorithm 559NeXTSTEP operating system 16noboolalpha stream manipulator 438noexcept keyword 571non-const member function 282non-const member function called on a
const object 282non-const member function on a non-
const object 282nonconstant pointer to constant data 241nonconstant pointer to nonconstant data
241noncontiguous memory layout of a deque
499nondeterministic random numbers 144none_of algorithm 533, 536, 558nonfatal logic error 32nonfatal runtime error 9non-member, friend function 313non-member function to overload an op-
438nth_element algorithm 558NULL 231null character ('\0') 253, 254, 426, 640,
645null pointer (0) 230, 232, 449, 639null statement 78null terminated 606null-terminated string 255, 421nullptr constant 230number of arguments 136number of elements in an array 245<numeric> 532numeric algorithms 553, 559<numeric> header 559numerical data type limits 141
Oobject 2, 3object (or instance) 5, 717object code 7, 62object leaves scope 272object of a derived class 377, 380object of a derived class is instantiated 369object-oriented analysis and design
692, 698, 702, 707, 726object-oriented language 6object-oriented programming (OOP) 2,
6, 16, 258, 343, 2object serialization 473object’s vtable pointer 410Objective-C 16objects contain only data 264oct stream manipulator 427, 432, 436octal (base-8) number system 427, 432,
649octal number 421, 436, 634, 650octal number system (base 8) 781off-by-one error 104offset 410offset from the beginning of a file 452offset to a pointer 250ofstream 446, 448, 450, 451, 461, 464,
6, 343open a file for input 448open a file for output 448open a nonexistent file 449open function of ofstream 448Open Handset Alliance 16open source 15, 16opened 445operand 22, 27, 28, 75operating system 15, 16operation (UML) 41operation compartment in a class diagram
708operation in the UML 41, 694, 707, 708,
711, 728, 731, 736operation parameter in the UML 44, 708,
optimizations on constants 281optimizing compiler 110, 154OR (||; logical OR) 123or operator keyword 668or_eq operator keyword 669order in which constructors and destruc-
tors are called 274order in which destructors are called 272order in which operators are applied to
their operands 180order of evaluation 181ordered associative containers 476, 500original format settings 440OS X 16ostream 452, 457, 466, 473ostream class 418
seekp function 452tellp function 452
ostream_iterator 481ostringstream class 609other character sets 592out-of-range array subscript 570out-of-range element 328out of scope 158out_of_bounds exception 493out_of_range class 335out_of_range exception 493, 514, 578,
595out_of_range exception class 226outer block 155
outer for structure 214out-of-bounds array elements 198output a floating-point value 432output buffering 443output data items of built-in type 419output format of floating-point numbers
437output iterator 482, 484, 521, 529, 542,
545output of char * variables 421output of characters 420output of floating-point values 421output of integers 421output of standard data types 420output of uppercase letters 421output sequence 481output stream 492output to string in memory 140outputting to strings in memory 609overflow 570overflow_error exception 578overhead of a function call 793overload the addition operator (+) 308overload unary operator ! 314overloaded [] operator 328overloaded << operator 314overloaded addition assignment operator
with a pointer parameter used to cubea variable’s value 235
with pointer parameters 233with reference parameters 165, 233
pass-by-reference with pointers 166pass-by-value 164, 165, 233, 234, 236,
243used to cube a variable’s value 234
passing arguments by value and by refer-ence 165
passing large objects 166passing options to a program 240“past the end” iterator 532peek function of istream 425percent sign (%) (modulus operator) 28perform a task 40perform an action 22performance 3PI 792, 793plus function object 554plus sign 434plus sign (+) indicating public visibility in
pointer notation 251pointer operators & and * 232pointer to a function 407pointer to an object 242pointer to void (void *) 249pointer variable 575pointer/offset notation 250pointer/subscript notation 250pointer-based string 606pointers and array subscripting 249, 250pointers and arrays 249pointers declared const 243pointers to dynamically allocated storage
293, 334pointer-to-member operators
.* 670->* 670
point-of-sale system 456poll analysis program 196polymorphic exception processing 572polymorphic programming 390, 410polymorphic screen manager 376polymorphically invoking functions in a
derived class 678polymorphism 373, 375polymorphism and references 407polynomial 31pop 587pop function of container adapters 509pop member function of
priority_queue 512pop member function of queue 511pop member function of stack 509pop_backmember function of list 498pop_front 494, 495, 500, 511pop_heap algorithm 551, 559Portability Tips overview xxivportable 2position number 186positional notation 781positional value 781, 782positional values in the decimal number
system 782postdecrement 96, 98postfix decrement operator 96postfix increment operator 96, 98postincrement 96, 320postincrement an iterator 484pow function 108, 110, 132power 132precedence 29, 31, 35, 98, 104, 124, 180precedence chart 35precedence not changed by overloading
309precedence of the conditional operator 75precision 90, 421, 426
format of a floating-point number 91precision function of ios_base 427precision of a floating-point value 85precision of floating-point numbers 427precision setting 428predecrement 96, 98predefined function objects 553predefined symbolic constants 796predicate function 265, 497, 523, 526,
prev_permutation algorithm 559prevent memory leak 577preventing headers from being included
more than once 259primary memory 8primitive data type promotion 90principal 108principle of least privilege 153, 239, 240,
243, 281, 450, 483print a line of text 20printer 9, 417printing
line of text with multiple statements23
multiple lines of text with a singlestatement 24
unsigned integer in bits 622priority_queue adapter class 512
empty function 513pop function 512push function 512size function 513top function 513
privateaccess specifier 47, 726base class 372base-class data cannot be accessed
from derived class 358inheritance 345members of a base class 345static data member 298
private libraries 7probability 141program development environment 6program execution stack 159program in the general 375program in the specific 375program termination 275, 276programmer-defined function
maximum 132promotion 90promotion hierarchy for built-in data
types 138promotion rules 138prompt 27, 88prompting message 443proprietary classes 372protected 361protected access specifier 258protected base class 372protected base-class data can be ac-
cessed from derived class 363protected inheritance 345, 372pseudorandom numbers 144public
keyword 726, 731method 260
public access specifier 39public base class 372public inheritance 343, 345public keyword 39public member of a derived class 346public services of a class 58
public static class member 298public static member function 298punctuation mark 644pure specifier 391pure virtual function 391, 407push 587push function of container adapters 509push member function of
priority_queue 512push member function of queue 511push member function of stack 509push_back member function of class
template vector 227push_backmember function of vector
488push_frontmember function of deque
499push_front member function of list
497push_heap algorithm 551, 559put file-position pointer 457, 462put member function 421, 422put pointer 452putback function of istream 425
Qqualified name 369<queue> header 140queue adapter class 511
back function 511empty function 511front function 511pop function 511push function 511size function 511
<queue> header 511, 512quotation marks 22
Rradians 131raise to a power 132rand function 141, 142RAND_MAX symbolic constant 141random integers in range 1 to 6 142random number 144random_shuffle algorithm 529, 531,
558random-access file 445, 457, 458, 464,
466random-access iterator 482, 483, 498,
501, 518, 524, 531, 536, 550, 551random-access iterator operations 484randomizing 144randomizing the die-rolling program 145range 481, 532range checking 324, 595range-based for 595, 608range-based for statement 200Rational Software Corporation 690Rational Unified Process™ 690raw data 456raw data processing 445rbegin member function of class
string 608rbegin member function of containers
479rbeginmember function of vector 490
814 Index
rdstate function of ios_base 442read 457, 464read a line of text 43read characters with getline 43read data sequentially from a file 450read function of istream 425read member function 426readmember function of istream 457,
471read-only variable 191Reading a random-access file sequentially
464Reading and printing a sequential file 450real number 85record 446, 466record format 459recover from errors 442recursion 175, 182, 183recursion step 176, 179recursive call 176, 179recursive function 175recursive function factorial 178recursive solution 184redundant parentheses 31, 123reference 229, 416, 479reference argument 233reference parameter 164, 165, 165reference to a constant 166reference to a private data member 276reference to an automatic variable 167reference to an int 165referencing array elements 251referencing array elements with the array
name and with pointers 251register declaration 154register storage-class specifier 152regular expression 17, 609reinterpret_cast operator 249, 458,
461, 464reinventing the wheel 3relational operator 32, 33relational operators >, <, >=, and <= 122release dynamically allocated memory 333remainder after integer division 28remove algorithm 526, 558remove member function of list 498remove_copy algorithm 524, 526, 558remove_copy_if algorithm 524, 527,
541, 558remove_if algorithm 524, 526, 558rend member function of class string
608rend member function of containers 479rend member function of vector 490repetition
replace_if algorithm 527, 529, 558replacement text 793, 796
for a macro or symbolic constant792, 794
requirements 5, 683, 688requirements document 688, 689requirements gathering 688requirements specification 684reset 514resize member function of class
string 601resource leak 572restore a stream’s state to “good” 442resumption model of exception handling
565rethrow an exception 567return a result 137Return key 27return message in the UML 720return statement 23, 47, 137, 176return type 40
void 40, 48return type in a function header 137return type in the UML 708, 713returning a reference from a function 167returning a reference to a private data
dependent 629right-to-left associativity 35Ritchie, Dennis 2robust application 561, 565role in the UML 695role name in the UML 695rolling a die 142rolling a six-sided die 6000 times 143rolling two dice 146, 147rotate algorithm 558rotate_copy algorithm 558round a floating-point number for display
purposes 91rounded rectangle (for representing a state
in a UML state diagram) 703rounding numbers 91, 131row subscript 211rows 211
RTTI (runtime type information) 411,414
rules of operator precedence 29Rumbaugh, James 684runtime error 9runtime type information (RTTI) 411,
414runtime_error class 562, 570, 578
what function 567rvalue ("right value") 128, 167, 328
SSalariedEmployee class header 397SalariedEmployee class implementa-
class 155file 155function 155function prototype 155namespace 155
scoping example 156screen 9, 21Screen class (ATM case study) 693, 695,
708, 714, 715, 716, 718, 720, 728screen-manager program 376scrutinize data 259search algorithm 558search functions of the string-handling li-
brary 651search key 500search_n algorithm 558searching 533searching arrays 209searching blocks of memory 655searching strings 639, 646second data member of pair 503second-degree polynomial 31secondary storage device 445secondary storage devices
CD 445DVD 445flash drive 445hard disk 445tape 445
second-degree polynomial 31“secret” implementation details 663security flaws 198seed 146seed function rand 144seek direction 452seek get 452
Index 815
seek put 452seekg function of istream 452, 472seekp function of ostream 452, 462select a substring 340selection statement 70, 73self assignment 333self-assignment 293self-documenting 26semicolon (;) 22, 34, 78, 791semicolon that terminates a structure def-
inition 617send a message to an object 5sentinel value 85, 89, 116separate interface from implementation
497back function 492empty function 493front function 492insert function 493
sequence diagram in the UML 691, 716sequence of messages in the UML 717sequence of random numbers 144sequence statement 70, 71, 73sequence-statement activity diagram 71sequential execution 70sequential file 445, 446, 447, 450, 456serialized object 473services of a class 49<set> header 140set a value 49set and get functions 48set associative container 504set function 288<set> header 501, 504set_intersection 545set_new_handler function 572, 574set of recursive calls to method Fibonac-
ci 181set operations of the Standard Library
543set_difference algorithm 543, 545,
559set_intersection algorithm 543,
545, 559set_new_handler specifying the func-
tion to call when new fails 574set_symmetric_difference algo-
109setw stream manipulator 254, 429, 433Shape class hierarchy 345shell prompt on Linux 9shift a range of numbers 142shifted, scaled integers 142shifted, scaled integers produced by 1 +
short data type 120short int data type 120showbase stream manipulator 432, 436showpoint stream manipulator 91, 432showpos stream manipulator 432, 434shrink_to_fit member function of
classes vector and deque 490shuffle algorithm 558shuffling algorithm 619side effect 164side effect of an expression 154, 164, 181sign extension 622sign left justified 432signal value 85signature 137, 171, 315signatures of overloaded prefix and postfix
increment operators 315significant digits 433simple condition 122, 124sin function 132sine 132single-argument constructor 339, 340single-entry/single-exit control statement
73, 74single inheritance 345, 677single-line comment 21single-precision floating-point number 89single quote 23single quote (') 252single-selection if statement 72, 76singly linked list 476, 494six-sided die 142size function of string 461size member function of array 187size member function of class string
64, 593size member function of containers 478size member function of
priority_queue 513size member function of queue 511size member function of stack 509size member function of vector 224size of a string 599size of a variable 152size of an array 244size_t 189, 458size_t type 244size_type 480sizeof 464, 651, 794sizeof operator 244, 245, 291
used to determine standard data typesizes 245
sizeof operator when applied to an ar-ray name returns the number of bytesin the array 245
skip remainder of switch statement 121skip remaining code in loop 122skipping whitespace 426, 432skipws stream manipulator 432small circle symbol 71smart pointer xxi, 18smartphone 16software engineering 58
data hiding 47, 49encapsulation 49reuse 54, 57separate interface from implementa-
tion 58set and get functions 48
Software Engineering Observations over-view xxiv
software life cycle 688software reuse 3, 343, 582, 672solid circle (for representing an initial
state in a UML diagram) in the UML703, 705
solid circle enclosed in an open circle (forrepresenting the end of a UML activitydiagram) 705
solid circle symbol 71solid diamonds (representing composi-
tion) in the UML 695sort algorithm 209, 533, 536, 558sort member function of list 497sort_heap algorithm 550, 559sorting 446, 533sorting and related algorithms 557sorting arrays 209sorting order 536, 540sorting strings 141source code 6, 372source-code file 54SourceForge 15spaces for padding 435space-time trade-off 466special character 253special characters 26specialization in the UML 734spiral 179splice member function of list 497splice_aftermember function of class
template forward_list 498sqrt function of <cmath> header 132square function 139square root 132, 428srand function 144srand( time( 0 ) ) 146<sstream> header 140, 609, 609stable_partition algorithm 558stable_sort algorithm 558<stack> header 140stack 158, 582stack adapter class 509
empty function 509pop function 509push function 509size function 509top function 509
class string 305container classes 476deque class template 499exception classes 579exception hierarchy 578
816 Index
Standard Library (cont.)headers 141, 791list class template 495map class template 508multimap class template 506multiset class template 501priority_queue adapter class 513queue adapter class templates 512set class template 504stack adapter class 509vector class template 487
standard output object (cout) 22, 418standard output stream (cout) 9standard output stream object (cout) 445standard stream libraries 418Standard Template Library 475state 690state bits 422state diagram for the ATM object 703state diagram in the UML 703state in the UML 690, 705state machine diagram in the UML 690,
703state of an object 698, 703statement 22, 40statement spread over several lines 35statement terminator (;) 22statements
static array initialization 198, 199static array initialization and auto-
matic array initialization 199static binding 384static_cast<int> 116static data member 207, 297, 298static data member tracking the num-
ber of objects of a class 300static data members save storage 298static keyword 154static linkage specifier 667static local object 273, 275static local variable 156, 158, 198, 521static member 298static member function 298static storage class 152static storage duration 153, 154, 155static storage-class specifier 152static_cast 98, 126static_cast (compile-time type-
accumulate 553STL exception types 493stod function 612stof function 612stoi function 612stol function 612stold function 612stoll function 612storage alignment 617storage duration 152
automatic 153dynamic 153static 153thread 153
storage unit 633storage-class specifiers 152
extern 152mutable 152register 152static 152
storage-unit boundary 633stoul function 612stoull function 612str member function 610str member function of class ostring-
stream 609straight-line form 29, 30strcat function of header <cstring>
639, 641strchr 651strcmp function of header <cstring>
string stream processing 609string::npos 603strings as full-fledged objects 252strlen function 640, 645strncat function 639, 641strncmp function 640, 642strncpy function 639, 640Stroustrup, B. 2strpbrk 651, 653strrchr 651, 653strspn 651, 654strstr 651, 654strtod 646, 648strtok function 640, 644strtol 647, 649, 649strtoul 647, 650
Index 817
struct 616structure 616, 792structure definition 616, 630structure members default to private
access 616structure name 616structure of a system 702, 703structure type 616structured programming 70student-poll-analysis program 196subclass 343subobject of a base class 678subproblem 176subscript 186subscript 0 (zero) 186subscript operator 500subscript operator [] 595subscript operator [] used with strings
593subscript operator for map 507subscript out of range 493subscript through a vector 493subscripted name used as an rvalue 328subscripting 498subscripting with a pointer and an offset
251substr 598substr member function of class
string 66, 598substrmember function of string 307substring 340substring length 340substring of a string 598subtract one pointer from another 247subtraction 29sum of the elements of an array 193summing integers with the for statement
107superclass 343survey 196, 198swap algorithm 538, 558swap member function of class string
598swap member function of containers 478swap member function of list 498swap_ranges algorithm 537, 538, 558swapping strings 598swapping two strings 598switch logic 390switch multiple-selection statement
112, 119switch multiple-selection statement ac-
tivity diagram with break statements120
symbol 592symbol values 781symbolic constant 791, 792, 794, 796symbolic constant NDEBUG 797symbolic constant PI 793synchronize operation of an istream and
Ttab 35tab escape sequence \t 118Tab key 22tab stop 23table of values 211tablet computer 16tabular format 189tails 142tan function 132tangent 132tape 445tellg function of istream 452tellp function of ostream 452template 792
default type argument for a type pa-rameter 589
template definition 174template function 173template keyword 173, 583template parameter 583template parameter list 173temporary object 337temporary value 90, 139terminate a program 574terminate normally 449terminate successfully 23terminating condition 177terminating null character 253, 254, 607,
640, 645terminating right brace (}) of a block 155termination condition 198termination housekeeping 272termination model of exception handling
565termination test 182ternary conditional operator (?:) 181ternary operator 75test 514test characters 140test state bits after an I/O operation 422text editor 450text file 466text-printing program 20text substitution 793this pointer 291, 293, 301, 334this pointer used explicitly 291this pointer used implicitly and explicit-
ly to access members of an object 292thread storage duration 153throw an exception 226, 260, 261, 564throw exceptions derived from standard
exceptions 579throw exceptions not derived from stan-
dard exceptions 579throw keyword 566throw point 565throw standard exceptions 579tie an input stream to an output stream
443tilde character (~) 272Time class containing a constructor with
default arguments 266Time class definition 258Time class definition modified to enable
cascaded member-function calls 294Time class member-function definitions
259
Time class member-function definitions,including a constructor that takes ar-guments 267
time function 146__TIME__ predefined symbolic constant
797time source file is compiled 797to_string function 612token 640, 644tokenizing strings 639, 644tolower 634, 636top member function of
priority_queue 513top member function of stack 509total 154toupper 634, 636trailing return type 557trailing return type (function) 175trailing return types 175trailing zeros 432Transaction class (ATM case study)
733, 734, 735, 738, 772transaction processing 505transaction-processing program 466transaction-processing system 456transfer of control 70transform algorithm 529, 533, 558transition 71transition arrow 71, 74, 78, 79transition between states in the UML 703translation 7translation unit 667traversal 607trigonometric cosine 131trigonometric sine 132trigonometric tangent 132true 32true 73, 74, 75truncate 28, 83, 90, 448truncate fractional part of a double 138truth table 123
notation 788twos position 783tying an output stream to an input stream
443type checking 793, 794type field 473type information 473type name (enumerations) 149type of a variable 152type of the this pointer 292type parameter 173, 583, 589type-safe linkage 171type_info class 413typedef 418, 592, 609, 618
41, 683, 684, 690, 694, 701, 702, 733action expression 71action state 71activity diagram 70, 71, 78arrow 71attribute 41class diagram 41constructor in a class diagram 54data types 44decision symbol 74diagram 690diamond symbol 71, 74dotted line 71final state 71guard condition 74guillemets (« and ») 54initial state 71merge symbol 79minus sign (–) 50note 71plus sign (+) 41public operation 41Resource Center
(www.deitel.com/UML/) 691small circle symbol 71solid circle symbol 71String type 44transition 71transition arrow 71, 74, 78, 79
UML activity diagram 105solid circle (for representing an initial
state) in the UML 705solid circle enclosed in an open circle
(for representing the end of an ac-tivity) in the UML 705
UML class diagramattribute compartment 701constructor 54operation compartment 708
unary plus (+) operator 90unary predicate function 497, 526, 529unary scope resolution operator (::) 169unbuffered output 420unbuffered standard error stream 418#undef preprocessing directive 794, 796undefined area in memory 618underflow_error exception 579underlying container 509underlying data structure 512underscore ( _ ) 26unformatted I/O 417, 418, 425unformatted output 420, 422Unicode 592Unicode character set 417Unified Modeling Language (UML) 6,
683, 684, 690, 694, 701, 702, 733uniform initialization 94uniform_int_distribution 151unincremented copy of an object 321unique algorithm 538, 540, 558unique keys 500, 504, 507unique member function of list 498unique_copy algorithm 541, 542, 558unique_ptr class 575
built-in array 578universal-time format 260UNIX 449unnamed bit field 633unnamed bit field with a zero width 633unnamed namespace 667unordered associative containers 476,
477, 500<unordered_map> header 140unordered_map class template 477, 507unordered_multimap class template
477, 505unordered_multiset class template
477, 501<unordered_set> header 140unordered_set class template 477, 504unscoped enum 150unsigned char data type 139unsigned data type 139, 145unsigned int 91unsigned int data type 139, 145unsigned int fundamental type 82unsigned integer in bits 622unsigned long 178, 650unsigned long data type 138unsigned long int 177, 178unsigned long int data type 138unsigned long long data type 138unsigned long long int 178unsigned long long int data type 138unsigned short data type 139unsigned short int data type 139untie an input stream from an output
stream 443unwinding the function call stack 568update records in place 456upper_bound algorithm 548, 558upper_bound function of associative
container 503uppercase letter 26, 140, 634, 636uppercase stream manipulator 432,
436, 438use case diagram in the UML 689, 690use case in the UML 688, 689
use case modeling 688user-defined class name 39user-defined function 132user-defined type 40, 149, 337using a dynamically allocated ostring-stream object 610
using a function template 173Using a static data member to maintain
a count of the number of objects of aclass 299
using an iterator to output a string 608using arrays instead of switch 195using declaration 34
in headers 56using directive 34, 665
in headers 56using function swap to swap twostrings 598
using Standard Library functions to per-form a heapsort 548
Using virtual base classes 680<utility> header 141utility function 265
Vvalidation 64validity checking 64value 27value initialize 238value of a variable 152value of an array element 187value_type 479variable 25variable name
argument 44parameter 44
variadic template 504<vector> header 140vector class 221
capacity function 488, 488crbegin function 490crend function 490push_back function 488push_front function 488rbegin function 490rend function 490
vector class template 186, 486push_back member function 227shrink_to_fit member function
490vector class template element-manipu-
lation functions 490<vector> header 221verb phrase in requirements specification
707vertical spacing 102vertical tab (‘v’) 634, 637vi 6virtual base class 661, 678, 679, 680,
681virtual destructor 389virtual function 375, 383, 407, 409,
visibility in the UML 726visibility marker in the UML 726Visual Studio 2012 Express Edition 7void * 249, 655void keyword 40, 48void return type 138volatile qualifier 661volume of a cube 164vtable 407, 409, 410vtable pointer 410
W“walk off” either end of an array 323warning message 66waterfall model 688wchar_t 592wchar_t character type 418“weakest” iterator type 482, 519what member function of an exception
object 226what virtual function of class exception
562, 567, 573
while repetition statement 72, 78, 102,110
while statement activity diagram 79whitespace characters 21, 22, 35, 422,
423, 426, 634, 637, 791, 796whole/part relationship 695width implicitly set to 0 429width member function of class
ios_base 429width of a bit field 630width of random number range 146width setting 429Windows 15, 116Windows operating system 15Windows Phone 7 15Withdrawal class (ATM case study) 693,