Programming Principles And Practice Using C Third Edition Bjarne Stroustrup download
Programming Principles And Practice Using C Third Edition Bjarne Stroustrup download
https://ebookbell.com/product/programming-principles-and-
practice-using-c-third-edition-bjarne-stroustrup-56321976
https://ebookbell.com/product/programming-principles-and-practice-
using-c-third-edition-3rd-edition-bjarne-stroustrup-56321970
https://ebookbell.com/product/programming-principles-and-practice-
using-c-bjarne-stroustrup-47936612
https://ebookbell.com/product/programming-principles-and-practice-
using-c-2nd-edition-bookmarks-2nd-edition-bjarne-stroustrup-23267128
https://ebookbell.com/product/programming-principles-and-practice-
using-c-1st-edition-bjarne-stroustrup-2424916
Programming Principles And Practice Using C 2nd Edition Bjarne
Stroustrup Stroustrup
https://ebookbell.com/product/programming-principles-and-practice-
using-c-2nd-edition-bjarne-stroustrup-stroustrup-22795670
https://ebookbell.com/product/programming-principles-and-practice-
using-c-2nd-edition-bjarne-stroustrup-35048356
https://ebookbell.com/product/programming-principles-and-practice-
using-c-3rd-edition-bjarne-stroustrup-56721742
https://ebookbell.com/product/programming-principles-and-practice-
using-c-2nd-edition-bjarne-stroustrup-36192818
https://ebookbell.com/product/programming-principles-and-practice-
using-c-2nd-edition-bjarne-stroustrup-chenjin5com-36192820
About This eBook
ePUB is an open, industry-standard format for eBooks. However, support
of ePUB and its many features varies across reading devices and applications.
Use your device or app settings to customize the presentation to your liking.
Settings that you can customize often include font, font size, single or double
column, landscape or portrait mode, and figures that you can click or tap to
enlarge. For additional information about the settings and features on your
reading device or app, visit the device manufacturer’s Web site.
Many titles include programming code or configuration examples. To
optimize the presentation of these elements, view the eBook in single-
column, landscape mode and adjust the font size to the smallest setting. In
addition to presenting code and configurations in the reflowable text format,
we have included images of the code that mimic the presentation found in the
print book; therefore, where the reflowable format may compromise the
presentation of the code listing, you will see a “Click here to view code
image” link. Click the link to view the print-fidelity code image. To return to
the previous page viewed, click the Back button on your device or app.
Programming: Principles and
Practice Using C++
Third Edition
Bjarne Stroustrup
The author and publisher have taken care in the preparation of this book, but
make no expressed or implied warranty of any kind and assume no
responsibility for errors or omissions. No liability is assumed for incidental or
consequential damages in connection with or arising out of the use of the
information or programs contained herein.
For information about buying this title in bulk quantities, or for special sales
opportunities (which may include electronic versions; custom cover designs;
and content particular to your business, training goals, marketing focus, or
branding interests), please contact our corporate sales department at
[email protected] or (800) 382-3419.
ISBN-13: 978-0-13-830868-1
ISBN-10: 0-13-83086-3
First printing, May 2024
$PrintCode
Contents
Preface
1 Hello, World!
1.1 Programs
1.2 The classic first program
1.3 Compilation
1.4 Linking
1.5 Programming environments
3 Computation
3.1 Computation
3.2 Objectives and tools
3.3 Expressions
3.4 Statements
3.5 Functions
3.6 vector
3.7 Language features
4 Errors!
4.1 Introduction
4.2 Sources of errors
4.3 Compile-time errors
4.4 Link-time errors
4.5 Run-time errors
4.6 Exceptions
4.7 Avoiding and finding errors
5 Writing a Program
5.1 A problem
5.2 Thinking about the problem
5.3 Back to the calculator!
5.4 Back to the drawing board
5.5 Turning a grammar into code
5.6 Trying the first version
5.7 Trying the second version
5.8 Token streams
5.9 Program structure
6 Completing a Program
6.1 Introduction
6.2 Input and output
6.3 Error handling
6.4 Negative numbers
6.5 Remainder: %
6.6 Cleaning up the code
6.7 Recovering from errors
6.8 Variables
10 A Display Model
10.1 Why graphics?
10.2 A display model
10.3 A first example
10.4 Using a GUI library
10.5 Coordinates
10.6 Shapes
10.7 Using Shape primitives
10.8 Getting the first example to run
11 Graphics Classes
11.1 Overview of graphics classes
11.2 Point and Line
11.3 Lines
11.4 Color
11.5 Line_style
11.6 Polylines
11.7 Closed shapes
11.8 Text
11.9 Mark
11.10 Image
12 Class Design
12.1 Design principles
12.2 Shape
12.3 Base and derived classes
12.4 Other Shape functions
12.5 Benefits of object-oriented programming
17 Essential Operations
17.1 Introduction
17.2 Access to elements
17.3 List initialization
17.4 Copying and moving
17.5 Essential operations
17.6 Other useful operations
17.7 Remaining Vector problems
17.8 Changing size
17.9 Our Vector so far
21 Algorithms
21.1 Standard-library algorithms
21.2 Function objects
21.3 Numerical algorithms
21.4 Copying
21.5 Sorting and searching
Index
Preface
Damn the
torpedoes!
Full speed ahead.
– Admiral
Farragut
Previous Editions
The third edition of Programming: Principles and Practice Using C++ is
about half the size of the second edition. Students having to carry the book
will appreciate the lighter weight. The reason for the reduced size is simply
that more information about C++ and its standard library is available on the
Web. The essence of the book that is generally used in a course in
programming is in this third edition (“PPP3”), updated to C++20 plus a bit of
C++23. The fourth part of the previous edition (“PPP2”) was designed to
provide extra information for students to look up when needed and is
available on the Web:
Where I felt it useful to reference these chapters, the references look like this:
PPP2.Ch22 or PPP2.§27.1.
Acknowledgments
Special thanks to the people who reviewed drafts of this book and suggested
many improvements: Clovis L. Tondo, Jose Daniel Garcia Sanchez, J.C. van
Winkel, and Ville Voutilainen. Also, Ville Voutilainen did the non-trivial
mapping of the GUI/Graphics interface library to Qt, making it portable to an
amazing range of systems.
Also, thanks to the many people who contributed to the first and second
editions of this book. Many of their comments are reflected in this third
edition.
0
eiπ + 1
– Leonhard
Euler
The use of CC, AA, and XX, rather than a single token in different colors, is
to help where colors are not easy to distinguish.
In addition, at the end of each chapter we offer some help to solidify what’s
learned:
Review: At the end of each chapter, you’ll find a set of review questions.
They are intended to point you to the key ideas explained in the chapter.
One way to look at the review questions is as a complement to the
exercises: the exercises focus on the practical aspects of programming,
whereas the review questions try to help you articulate the ideas and
concepts. In that, they resemble good interview questions.
Terms: A section at the end of each chapter presents the basic
vocabulary of programming and of C++. If you want to understand what
people say about programming topics and to articulate your own ideas,
you should know what each term means.
Postscript: A paragraph intended to provide some perspective for the
material presented.
In addition, we recommend that you take part in a small project (and more if
time allows for it). A project is intended to produce a complete useful
program. Ideally, a project is done by a small group of people (e.g., three
people) working together (e.g., while progressing through the later chapters
of the book). Most people find such projects the most fun and that they tie
everything together.
CC
Learning involves repetition. Our ideal is to make every important point at
least twice and to reinforce it with exercises.
Program organization
Debugging and testing
Class design
Computation
Function and algorithm design
Graphics (two-dimensional only)
Graphical user interfaces (GUIs)
Files and stream input and output (I/O)
Memory management
Design and programming ideals
The C++ standard library
Software development strategies
To keep the book lighter than the small laptop on which it is written, some
supplementary topics from the second edition are placed on the Web (§0.4.1):
0.3.1 Portability
CC
It is common to write C++ to run on a variety of machines. Major C++
applications run on machines we haven’t ever heard of! We consider the use
of C++ on a variety of machine architectures and operating systems most
important. Essentially every example in this book is not only ISO Standard
C++, but also portable. By portable, we mean that we make no assumptions
about the computer, the operating system, and the compiler beyond that an
up-to-date standard-conforming C++ implementation is available. Unless
specifically stated, the code we present should work on every C++
implementation and has been tested on several machines and operating
systems.
The details of how to compile, link, and run a C++ program differ from
system to system. Also, most systems offer you a choice of compilers and
tools. Explaining the many and often mutating tool sets is beyond the scope
of the book. We might add some such information to the PPP support Web
site (§0.4).
If you have trouble with one of the popular, but rather elaborate, IDEs
(integrated development environments), we suggest you try working from the
command line; it’s surprisingly simple. For example, here is the full set of
commands needed to compile, link, and execute a simple program consisting
of two source files, my_file1.cpp and my_file2.cpp, using the GNU C++
compiler on a Linux system:
Click here to view code image
c++ −o my_program my_file1.cpp my_file2.cpp
./my_program
0.3.2 Guarantees
Except when illustrating errors, the code in this book is type-safe (an object is
used only according to its definition). We follow the rules of The C++ Core
Guidelines to simplify programming and eliminate common errors. You can
find the Core Guidelines on the Web [CG] and rule checkers are available
when you need guaranteed conformance.
We don’t recommend that you delve into this while still a novice, but
consider it reassuring that the recommended styles and techniques illustrated
in this book have industrial backing. Once you are comfortable with C++ and
understand the potential errors (say after Chapter 16), we suggest you read
the introduction to the CG and try one of the CG checkers to see how they
can eliminate errors before they make it into running code.
0.6 Bibliography
Along with listing the publications mentioned in this chapter, this section also
includes publications you might find helpful.
Postscript
Each chapter provides a short “postscript” that attempts to give some
perspective on the information presented in the chapter. We do that with the
realization that the information can be – and often is – daunting and will only
be fully comprehended after doing exercises, reading further chapters (which
apply the ideas of the chapter), and a later review. Don’t panic! Relax; this is
natural and expected. You won’t become an expert in a day, but you can
become a reasonably competent programmer as you work your way through
the book. On the way, you’ll encounter much information, many examples,
and many techniques that many thousands of programmers have found
stimulating and fun.
Part I
The Basics
Hello, World!
Programming
is learned by
writing
programs.
– Brian
Kernighan
§1.1 Programs
§1.2 The classic first program
§1.3 Compilation
§1.4 Linking
§1.5 Programming environments
1.1 Programs
To get a computer to do something, you (or someone else) have to tell it
exactly – in excruciating detail – what to do. Such a description of “what to
do” is called a program, and programming is the activity of writing and
testing such programs.
In a sense, we have all programmed before. After all, we have given
descriptions of tasks to be done, such as “how to drive to the nearest cinema,”
“how to find the upstairs bathroom,” and “how to heat a meal in the
microwave.” The difference between such descriptions and programs is one
of degree of precision: humans tend to compensate for poor instructions by
using common sense, but computers don’t. For example, “turn right in the
corridor, up the stairs, it’ll be on your left” is probably a fine description of
how to get to the upstairs bathroom. However, when you look at those simple
instructions, you’ll find the grammar sloppy and the instructions incomplete.
A human easily compensates. For example, assume that you are sitting at the
table and ask for directions to the bathroom. You don’t need to be told to get
up from your chair to get to the corridor, somehow walk around (and not
across or under) the table, not to step on the cat, etc. You’ll not have to be
told not to bring your knife and fork or to remember to switch on the light so
that you can see the stairs. Opening the door to the bathroom before entering
is probably also something you don’t have to be told.
In contrast, computers are really dumb. They have to have everything
described precisely and in detail. Consider again “turn right in the corridor,
up the stairs, it’ll be on your left.” Where is the corridor? What’s a corridor?
What is “turn right”? What stairs? How do I go up stairs? (One step at a
time? Two steps? Slide up the banister?) What is on my left? When will it be
on my left? To be able to describe “things” precisely for a computer, we need
a precisely defined language with a specific grammar (English is far too
loosely structured for that) and a well-defined vocabulary for the kinds of
actions we want performed. Such a language is called a programming
language, and C++ is a programming language designed for a wide selection
of programming tasks. When a computer can perform a complex task given
simple instructions, it is because someone has taught it to do so by providing
a program.
If you want greater philosophical detail about computers, programs, and
programming, see PPP2.Ch1 and PPP2.Ch22. Here, we start with a very
simple program and the tools and techniques you need to get it to run.
is a comment. Anything written after the token // (that’s the character /, called
“slash,” twice) on a line is a comment. Comments are ignored by the
compiler and written for the benefit of programmers who read the code. Here,
we used the comment to tell you what the beginning of that line actually did.
Comments are written to describe what the program is intended to do and
in general to provide information useful for humans that can’t be directly
expressed in code. The person most likely to benefit from the comments in
your code is you – when you come back to that code next week, or next year,
and have forgotten exactly why you wrote the code the way you did. So,
document your programs well. In §4.7.2.1 and §6.6.4, we’ll discuss what
makes good comments.
CC
A program is written for two audiences. Naturally, we write code for
computers to execute. However, we spend long hours reading and modifying
the code. Thus, programmers are another audience for programs. So, writing
code is also a form of human-to-human communication. In fact, it makes
sense to consider the human readers of our code our primary audience: if they
(we) don’t find the code reasonably easy to understand, the code is unlikely
to ever become correct. So, please don’t forget: code is for reading – do all
you can to make it readable.
The first line of the program is a typical comment; it simply tells the
human reader what the program is supposed to do:
Click here to view code image
// This program outputs the message "Hello, World!" to the monitor
Such comments are useful because the code itself says what the program
does, not what we meant it to do. Also, we can usually explain (roughly)
what a program should do to a human much more concisely than we can
express it (in detail) in code to a computer. Often such a comment is the first
part of the program we write. If nothing else, it reminds us what we are trying
to do.
The next line
import std;
CC
Every C++ program must have a function called main to tell it where to start
executing. A function is basically a named sequence of instructions for the
computer to execute in the order in which they are written. A function has
four parts:
A return type, here int (meaning “integer”), which specifies what kind of
result, if any, the function will return to whoever asked for it to be
executed. The word int is a reserved word in C++ (a keyword), so int
cannot be used as the name of anything else.
A name, here main.
A parameter list enclosed in parentheses (see §7.2 and §7.4), here (); in
this case, the parameter list is empty.
A function body enclosed in a set of “curly braces,” { }, which lists the
actions (called statements) that the function is to perform.
That’s not of much use, though, because it doesn’t do anything. The main()
(“the main function”) of our “Hello, World!” program has two statements in
its body:
Click here to view code image
std::cout << "Hello, World!\n"; // output "Hello, World!"
return 0;
First it’ll write Hello, World! to the screen, and then it will return a value 0
(zero) to whoever called it. Since main() is called by “the system,” we won’t
use that return value. However, on some systems (notably Unix/Linux) it can
be used to check whether the program succeeded. A zero (0) returned by
main() indicates that the program terminated successfully.
A part of a C++ program that specifies an action is called a statement.
1.3 Compilation
CC
C++ is a compiled language. That means that to get a program to run, you
must first translate it from the human-readable form to something a machine
can “understand.” That translation is done by a program called a compiler.
What you read and write is called source code or program text, and what the
computer executes is called object code or machine code. Typically, C++
source code files are given the suffix .cpp (e.g., hello_world.cpp) and object
code files are given the suffix .obj (on Windows) or .o (Linux). The plain
word code is therefore ambiguous and can cause confusion; use it with care
only when it is obvious what’s meant by it. Unless otherwise specified, we
use code to mean “source code” or even “the source code except the
comments,” because comments really are there just for us humans and are not
seen by the compiler generating object code.
The compiler reads your source code and tries to make sense of what you
wrote. It looks to see if your program is grammatically correct, if every word
has a defined meaning, and if there is anything obviously wrong that can be
detected without trying to actually execute the program. You’ll find that
compilers are rather picky about syntax. Leaving out any detail of our
program, such as importing a module file, a semicolon, or a curly brace, will
cause errors. Similarly, the compiler has absolutely zero tolerance for spelling
mistakes. Let us illustrate this with a series of examples, each of which has a
single small error. Each error is an example of a kind of mistake we often
make:
Click here to view code image
int main()
{
std::cout << "Hello, World!\n";
return 0;
}
We didn’t provide the compiler with anything to explain what std::cout was,
so the compiler complains. To correct that, let’s add the import:
Click here to view code image
import std;
int main()
{
cout << "Hello, World!\n";
return 0;
}
The compiler again complains: We made the standard library available but
forgot to tell the compiler to look in std for cout. The compiler also objects to
this:
Click here to view code image
import std;
int main()
{
std::cout << "Hello, World!\n;
return 0;
}
We didn’t terminate the string with a ". The compiler also objects to this:
Click here to view code image
import std;
integer main()
{
std::cout << "Hello, World!\n";
return 0;
}
The abbreviation int is used in C++ rather than the word integer. The compiler
doesn’t like this:
Click here to view code image
import std;
int main()
{
std::cout < "Hello, World!\n";
return 0;
}
We used < (the less-than operator) rather than << (the output operator).
Another error:
Click here to view code image
import std;
int main()
{
std::cout << 'Hello, World!\n';
return 0;
}
We used single quotes rather than double quotes to delimit the string. Finally,
the compiler gives an error for this:
Click here to view code image
import std;
int main()
{
std::cout << "Hello, World!\n"
return 0;
}
For historical reasons, we can leave out the return statement in main (and only
in main) and it is as if we had written return 0; and the end of main’s body to
indicate successful completion.
Why do we spend two pages of good space and minutes of your precious
time showing you examples of trivial errors in a trivial program? To make the
point that you – like all programmers – will spend a lot of time looking for
errors in program source text. Most of the time, we look at text with errors in
Random documents with unrelated
content Scribd suggests to you:
to my mind; and I may further observe, that while the
people in general recommended the colonies to
foreigners as especially worthy of their notice, I do not
remember meeting with one individual who could point
out any specific results, and few who would distinctly
assert that there was any increasing and permanent
benefit to the community from them.
It is probable that unless some great change is made
in the present system, the colonies will be ultimately
abandoned, or merge into the establishments for
compulsory labour: in other words, the society will
become the farmers, and the present colonists merely
agricultural labourers, differing only from the ordinary
labourer, inasmuch as they will work under the penalty
of being treated as vagabonds in case of contumacy.
The observations I have hitherto made apply only to
the free colonies. In the mendicity or compulsory
colonies, the poor are assembled in large
establishments, and cultivate the ground, either by task
or day labour, and attend the cattle, &c., under the
direction of certain officers; it is, in fact, a species of
agricultural workhouse.
The following is a Return of the compulsory
establishment at Merxplas. (p. 20.)
Rouen.
Section 3.—Dormitories.
Section 4.—Refectories.
Section 4.—Workshops.
Britany.
Finisterre 524,396
Côtes-du-Nord 598,872
Morbihan 433,522
Ille-et-Vilaine 547,052
Loire Inférieure 470,093
2,573,935
LOIRE INFERIEURE.
Nantes.
Vagrants.
Population of
the Department,
In the department Loire Inférieure there 470,093.
is no asylum for mendicants; but Nantes has Population of
Nantes, 87,191.
a species of workhouse, “St. Joseph’s
House,” supported entirely by private subscriptions. To
this house the tribunals often send vagabonds, in virtue
of the 274th article of the Penal Code, although the
directors of the establishment have contested, and still
contest, the right assumed by the judges to do so; and
they never receive any person so sent as a criminal to
be detained a certain number of days at labour as if in
a prison, but merely give him a refuge as an act of
charity, and liberty to leave the place, if he likes to go
before the time expires. The number of vagrants that
formerly infested Nantes (strangers to the department
as well as to the city) have decreased to about a tenth
part since begging in the streets was prohibited, and
the paupers sent to this establishment.
The hospitals of Nantes receive all workmen,
travellers, and needy strangers, that fall sick in the city
(if foreigners, at the charge to their consuls of 1s. 3d.
sterling per day for men, and 10d. for women.) If a
man, (and his family also,) being destitute, wishes to
return to his native place, and has not rendered himself
liable to be committed as a vagrant, the préfet has the
power to give a passport to him for that place; on the
production of which at the mairie of the commune from
which he sets out he receives from the public funds of
the department three halfpence per league for the
distance from thence to the next place he is to be
relieved at, and so on to the end of his journey, each
place he has to stop at being set down on his passport;
if he deviates from the route designated, he is arrested
as a vagabond.
There is in France throughout the whole country a
general union for each of several trades, the
carpenters, bakers, masons, tailors, &c. In each city or
town of consequence, each society has a member who
is called “the mother,” who receives the weekly
contributions of those who reside in that place, affords
relief to all of its members passing through it, and is
obliged to procure work for the applicant, or support
him at a fixed rate, established by their bye-laws, until
a situation be provided for him there or elsewhere.
Those unions sometimes assume a very dangerous
power, by compelling masters to hire all their members
that are without work, before they engage one man
who does not belong to them.
Destitute Able-bodied.
Sick.
ebookbell.com