Full Chapter Programming Principles and Practice Using C Third Edition Bjarne Stroustrup PDF
Full Chapter Programming Principles and Practice Using C Third Edition Bjarne Stroustrup PDF
https://textbookfull.com/product/programming-principles-and-
practice-using-c-second-edition-stroustrup/
https://textbookfull.com/product/programming-principles-and-
practice-using-c-3rd-edition-stroustrup/
https://textbookfull.com/product/computer-graphics-programming-
in-opengl-using-c-third-edition-gordon-phd/
https://textbookfull.com/product/a-tour-of-c-stroustrup/
A Tour of C++ Stroustrup
https://textbookfull.com/product/a-tour-of-c-stroustrup-2/
https://textbookfull.com/product/pavement-engineering-principles-
and-practice-third-edition-el-korchi/
https://textbookfull.com/product/a-tour-of-c-3rd-edition-
stroustrup-b/
https://textbookfull.com/product/tour-of-c-a-c-in-depth-
series-3rd-edition-stroustrup/
https://textbookfull.com/product/post-tensioned-concrete-
principles-and-practice-third-edition-k-dirk-bondy/
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.
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
18 Templates and Exceptions
18.1 Templates
18.2 Generalizing Vector
18.3 Range checking and exceptions
18.4 Resources and exceptions
18.5 Resource-management pointers
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:
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
CC
To ease review and to help you if you miss a key point during a first reading
where you have yet to discover which kind of information is crucial, we place three
kinds of “alert markers” in the margin:
AA
This book is designed to be read chapter by chapter from the beginning to the
end. Often, you’ll want to go back to look at something a second or a third time. In
fact, that’s the only sensible approach, as you’ll always dash past some details that
you don’t yet see the point in. In such cases, you’ll eventually go back again.
Despite the index and the cross-references, this is not a book that you can open to
any page and start reading with any expectation of success. Each section and each
chapter assume understanding of what came before.
Each chapter is a reasonably self-contained unit, meant to be read in “one
sitting” (logically, if not always feasible on a student’s tight schedule). That’s one
major criterion for separating the text into chapters. Other criteria include that a
chapter is a suitable unit for drills and exercises and that each chapter presents
some specific concept, idea, or technique. This plurality of criteria has left a few
chapters uncomfortably long, so please don’t take “in one sitting” too literally. In
particular, once you have thought about the review questions, done the drill, and
worked on a few exercises, you’ll often find that you have to go back to reread a
few sections.
A common praise for a textbook is “It answered all my questions just as I
thought of them!” That’s an ideal for minor technical questions, and early readers
have observed the phenomenon with this book. However, that cannot be the whole
ideal. We raise questions that a novice would probably not think of. We aim to ask
and answer questions that you need to consider when writing quality software for
the use of others. Learning to ask the right (often hard) questions is an essential
part of learning to think as a programmer. Asking only the easy and obvious
questions would make you feel good, but it wouldn’t help make you a programmer.
We try to respect your intelligence and to be considerate about your time. In our
presentation, we aim for professionalism rather than cuteness, and we’d rather
understate a point than hype it. We try not to exaggerate the importance of a
programming technique or a language feature, but please don’t underestimate a
simple statement like “This is often useful.” If we quietly emphasize that something
is important, we mean that you’ll sooner or later waste days if you don’t master it.
Our use of humor is more limited than we would have preferred, but experience
shows that people’s ideas of what is funny differ dramatically and that a failed
attempt at humor can be confusing.
CC
We do not pretend that our ideas or the tools offered are perfect. No tool, library,
language, or technique is “the solution” to all of the many challenges facing a
programmer. At best, a language can help you to develop and express your solution.
We try hard to avoid “white lies”; that is, we refrain from oversimplified
explanations that are clear and easy to understand, but not true in the context of
real languages and real problems.
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.
AA
Eventually, you should learn another programming language. We don’t consider
it possible to be a professional in the realm of software – even if you are not
primarily a programmer – without knowing more than one language. Why? No large
program is written in a single language. Also, different languages typically differ in
the way code is thought about and programs are constructed. Design techniques,
availability of libraries, and the way programs are built differ, sometimes
dramatically. Even when the syntaxes of two languages are similar, the similarity is
typically only skin deep. Performance, detection of errors, and constraints on what
can be expressed typically differ. This is similar to the ways natural languages and
cultures differ. Knowing only a single language and a single culture implies the
danger of thinking that “the way we do things” is the only way or the only good
way. That way opportunities are missed, and sub-optimal programs are produced.
One of the best ways to avoid such problems is to know several languages
(programming languages and natural languages).
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):
Working our way through the chapters, we cover the programming techniques
called procedural programming (as with the C programming language), data
abstraction, object-oriented programming, and generic programming. The main
topic of this book is programming, that is, the ideals, techniques, and tools of
expressing ideas in code. The C++ programming language is our main tool, so we
describe many of C++’s facilities in some detail. But please remember that C++ is
just a tool, rather than the main topic of this book. This is “programming using
C++,” not “C++ with a bit of programming theory.”
Each topic we address serves at least two purposes: it presents a technique,
concept, or principle and also a practical language or library feature. For example,
we use the interface to a two-dimensional graphics system to illustrate the use of
classes and inheritance. This allows us to be economical with space (and your time)
and also to emphasize that programming is more than simply slinging code together
to get a result as quickly as possible. The C++ standard library is a major source of
such “double duty” examples – many even do triple duty. For example, we introduce
the standard-library vector, use it to illustrate widely useful design techniques, and
show many of the programming techniques used to implement it. One of our aims
is to show you how major library facilities are implemented and how they map to
hardware. We insist that craftsmen must understand their tools, not just consider
them “magical.”
Some topics will be of greater interest to some programmers than to others.
However, we encourage you not to prejudge your needs (how would you know what
you’ll need in the future?) and at least look at every chapter. If you read this book
as part of a course, your teacher will guide your selection.
CC
We characterize our approach as “depth-first.” It is also “concrete-first” and
“concept-based.” First, we quickly (well, relatively quickly, Chapter 1 to Chapter 9)
assemble a set of skills needed for writing small practical programs. In doing so, we
present a lot of tools and techniques in minimal detail. We focus on simple concrete
code examples because people grasp the concrete faster than the abstract. That’s
simply the way most humans learn. At this initial stage, you should not expect to
understand every little detail. In particular, you’ll find that trying something slightly
different from what just worked can have “mysterious” effects. Do try, though!
Please do the drills and exercises we provide. Just remember that early on you just
don’t have the concepts and skills to accurately estimate what’s simple and what’s
complicated; expect surprises and learn from them.
AA
We move fast in this initial phase – we want to get you to the point where you
can write interesting programs as fast as possible. Someone will argue, “We must
move slowly and carefully; we must walk before we can run!” But have you ever
watched a baby learning to walk? Babies really do run by themselves before they
learn the finer skills of slow, controlled walking. Similarly, you will dash ahead,
occasionally stumbling, to get a feel of programming before slowing down to gain
the necessary finer control and understanding. You must run before you can walk!
XX
It is essential that you don’t get stuck in an attempt to learn “everything” about
some language detail or technique. For example, you could memorize all of C++’s
built-in types and all the rules for their use. Of course you could, and doing so
might make you feel knowledgeable. However, it would not make you a
programmer. Skipping details will get you “burned” occasionally for lack of
knowledge, but it is the fastest way to gain the perspective needed to write good
programs. Note that our approach is essentially the one used by children learning
their native language and also the most effective approach used to learn a foreign
language. We encourage you to seek help from teachers, friends, colleagues,
Mentors, etc. on the inevitable occasions when you are stuck. Be assured that
nothing in these early chapters is fundamentally difficult. However, much will be
unfamiliar and might therefore feel difficult at first.
Later, we build on your initial skills to broaden your base of knowledge. We use
examples and exercises to solidify your understanding, and to provide a conceptual
base for programming.
AA
We place a heavy emphasis on ideals and reasons. You need ideals to guide you
when you look for practical solutions – to know when a solution is good and
principled. You need to understand the reasons behind those ideals to understand
why they should be your ideals, why aiming for them will help you and the users of
your code. Nobody should be satisfied with “because that’s the way it is” as an
explanation. More importantly, an understanding of ideals and reasons allows you to
generalize from what you know to new situations and to combine ideas and tools in
novel ways to address new problems. Knowing “why” is an essential part of
acquiring programming skills. Conversely, just memorizing lots of poorly understood
rules is limiting, a source of errors, and a massive waste of time. We consider your
time precious and try not to waste it.
Many C++ language-technical details are banished to other sources, mostly on
the Web (§0.4.1). We assume that you have the initiative to search out information
when needed. Use the index and the table of contents. Don’t forget the online help
facilities of your compiler. Remember, though, to consider every Web resource
highly suspect until you have reason to believe better of it. Many an authoritative-
looking Web site is put up by a programming novice or someone with something to
sell. Others are simply outdated. We provide a collection of links and information on
our support Web site: www.stroustrup.com/programming.xhtml.
Please don’t be too impatient for “realistic” examples. Our ideal example is the
shortest and simplest code that directly illustrates a language facility, a concept, or
a technique. Most real-world examples are far messier than ours, yet do not consist
of more than a combination of what we demonstrate. Successful commercial
programs with hundreds of thousands of lines of code are based on techniques that
we illustrate in a dozen 50-line programs. The fastest way to understand real-world
code is through a good understanding of the fundamentals.
We do not use “cute examples involving cuddly animals” to illustrate our points.
We assume that you aim to write real programs to be used by real people, so every
example that is not presented as specifically language-technical is taken from a
real-world use. Our basic tone is that of professionals addressing (future)
professionals.
C++ rests on two pillars:
Efficient direct access to machine resources: making C++ effective for low-
level, machine-near, programming as is essential in many application domains.
Powerful (Zero-overhead) abstraction mechanisms: making it possible to
escape the error-prone low-level programming by providing elegant, flexible,
and type-and-resource-safe, yet efficient facilities needed for higher-level
programming.