Programming Principles and Practice Using C
Third Edition Bjarne Stroustrup download
https://textbookfull.com/product/programming-principles-and-
practice-using-c-third-edition-bjarne-stroustrup/
Download more ebook instantly today - get yours now at textbookfull.com
We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!
Programming: Principles and Practice Using C++ , Second
Edition Stroustrup
https://textbookfull.com/product/programming-principles-and-
practice-using-c-second-edition-stroustrup/
Programming Principles and Practice Using C 3rd
Edition Stroustrup
https://textbookfull.com/product/programming-principles-and-
practice-using-c-3rd-edition-stroustrup/
Computer Graphics Programming in OpenGL Using C++,
Third Edition Gordon Phd
https://textbookfull.com/product/computer-graphics-programming-
in-opengl-using-c-third-edition-gordon-phd/
A Tour of C++ Stroustrup
https://textbookfull.com/product/a-tour-of-c-stroustrup/
A Tour of C++ Stroustrup
https://textbookfull.com/product/a-tour-of-c-stroustrup-2/
Pavement Engineering: Principles and Practice, Third
Edition El-Korchi
https://textbookfull.com/product/pavement-engineering-principles-
and-practice-third-edition-el-korchi/
A Tour of C 3rd Edition Stroustrup B.
https://textbookfull.com/product/a-tour-of-c-3rd-edition-
stroustrup-b/
Tour of C A C In Depth Series 3rd Edition Stroustrup
https://textbookfull.com/product/tour-of-c-a-c-in-depth-
series-3rd-edition-stroustrup/
Post Tensioned Concrete Principles and Practice Third
Edition K. Dirk Bondy
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
Hoboken, New Jersey
Cover photo by Photowood Inc./Corbis.
Author photo courtesy of Bjarne Stroustrup.
Page 294: “Promenade a Skagen” by Peder Severin Kroyer.
Page 308: Photo of NASA’s Ingenuity Mars Helicopter, The National
Aeronautics and Space Administration (NASA).
Page 354: Photo of Hurricane Rita as seen from space, The National
Oceanic and Atmospheric Administration (NOAA).
Many of the designations used by manufacturers and sellers to
distinguish their products are claimed as trademarks. Where those
designations appear in this book, and the publisher was aware of a
trademark claim, the designations have been printed with initial
capital letters or in all capitals.
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
corpsales@pearsoned.com or (800) 382-3419.
For government sales inquiries, please contact
governmentsales@pearsoned.com.
For questions about sales outside the U.S., please contact
intlcs@pearson.com.
Visit us on the Web: informit.com/aw
Library of Congress Control Number: 2024932369
Copyright 2024 by Pearson Education, Inc.
All rights reserved. This publication is protected by copyright, and
permission must be obtained from the publisher prior to any
prohibited reproduction, storage in a retrieval system, or
transmission in any form or by any means, electronic, mechanical,
photocopying, recording, or likewise. For information regarding
permissions, request forms and the appropriate contacts within the
Pearson Education Global Rights & Permissions Department, please
visit www.pearson.com/permissions.
This book was typeset in Times and Helvetica by the author.
ISBN-13: 978-0-13-830868-1
ISBN-10: 0-13-83086-3
First printing, May 2024
$PrintCode
Contents
Preface
0 Notes to the Reader
0.1 The structure of this book
0.2 A philosophy of teaching and learning
0.3 ISO standard C++
0.4 PPP support
0.5 Author biography
0.6 Bibliography
Part I: The Basics
1 Hello, World!
1.1 Programs
1.2 The classic first program
1.3 Compilation
1.4 Linking
1.5 Programming environments
2 Objects, Types, and Values
2.1 Input
2.2 Variables
2.3 Input and type
2.4 Operations and operators
2.5 Assignment and initialization
2.6 Names
2.7 Types and objects
2.8 Type safety
2.9 Conversions
2.10 Type deduction: auto
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
7 Technicalities: Functions, etc.
7.1 Technicalities
7.2 Declarations and definitions
7.3 Scope
7.4 Function call and return
7.5 Order of evaluation
7.6 Namespaces
7.7 Modules and headers
8 Technicalities: Classes, etc.
8.1 User-defined types
8.2 Classes and members
8.3 Interface and implementation
8.4 Evolving a class: Date
8.5 Enumerations
8.6 Operator overloading
8.7 Class interfaces
Part II: Input and Output
9 Input and Output Streams
9.1 Input and output
9.2 The I/O stream model
9.3 Files
9.4 I/O error handling
9.5 Reading a single value
9.6 User-defined output operators
9.7 User-defined input operators
9.8 A standard input loop
9.9 Reading a structured file
9.10 Formatting
9.11 String streams
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
13 Graphing Functions and Data
13.1 Introduction
13.2 Graphing simple functions
13.3 Function
13.4 Axis
13.5 Approximation
13.6 Graphing data
14 Graphical User Interfaces
14.1 User-interface alternatives
14.2 The “Next” button
14.3 A simple window
14.4 Button and other Widgets
14.5 An example: drawing lines
14.6 Simple animation
14.7 Debugging GUI code
Part III: Data and Algorithms
15 Vector and Free Store
15.1 Introduction
15.2 vector basics
15.3 Memory, addresses, and pointers
15.4 Free store and pointers
15.5 Destructors
15.6 Access to elements
15.7 An example: lists
15.8 The this pointer
16 Arrays, Pointers, and References
16.1 Arrays
16.2 Pointers and references
16.3 C-style strings
16.4 Alternatives to pointer use
16.5 An example: palindromes
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
19 Containers and Iterators
19.1 Storing and processing data
19.2 Sequences and iterators
19.3 Linked lists
19.4 Generalizing Vector yet again
19.5 An example: a simple text editor
19.6 vector, list, and string
20 Maps and Sets
20.1 Associative containers
20.2 map
20.3 unordered_map
20.4 Timing
20.5 set
20.6 Container overview
20.7 Ranges and iterators
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
Programming is the art of expressing solutions to problems so that a
computer can execute those solutions. Much of the effort in
programming is spent finding and refining solutions. Often, a
problem is only fully understood through the process of
programming a solution for it.
This book is for someone who has never programmed before but
is willing to work hard to learn. It helps you understand the
principles and acquire the practical skills of programming using the
C++ programming language. It can also be used by someone with
some programming knowledge who wants a more thorough
grounding in programming principles and contemporary C++.
Why would you want to program? Our civilization runs on
software. Without understanding software, you are reduced to
believing in “magic” and will be locked out of many of the most
interesting, profitable, and socially useful technical fields of work.
When I talk about programming, I think of the whole spectrum of
computer programs from personal computer applications with GUIs
(graphical user interfaces), through engineering calculations and
embedded systems control applications (such as digital cameras,
cars, and cell phones), to text manipulation applications as found in
many humanities and business applications. Like mathematics,
programming – when done well – is a valuable intellectual exercise
that sharpens our ability to think. However, thanks to feedback from
the computer, programming is more concrete than most forms of
math and therefore accessible to more people. It is a way to reach
out and change the world – ideally for the better. Finally,
programming can be great fun.
There are many kinds of programming. This book aims to serve
those who want to write nontrivial programs for the use of others
and to do so responsibly, providing a decent level of system quality.
That is, I assume that you want to achieve a level of
professionalism. Consequently, I chose the topics for this book to
cover what is needed to get started with real-world programming,
not just what is easy to teach and learn. If you need a technique to
get basic work done right, I describe it, demonstrate concepts and
language facilities needed to support the technique, and provide
exercises for it. If you just want to understand toy programs or write
programs that just call code provided by others, you can get along
with far less than I present. In such cases, you will probably also be
better served by a language that’s simpler than C++. On the other
hand, I won’t waste your time with material of marginal practical
importance. If an idea is explained here, it’s because you’ll almost
certainly need it.
Programming is learned by writing programs. In this,
programming is similar to other endeavors with a practical
component. You cannot learn to swim, to play a musical instrument,
or to drive a car just from reading a book – you must practice. Nor
can you become a good programmer without reading and writing
lots of code. This book focuses on code examples closely tied to
explanatory text and diagrams. You need those to understand the
ideals, concepts, and principles of programming and to master the
language constructs used to express them. That’s essential, but by
itself, it will not give you the practical skills of programming. For
that, you need to do the exercises and get used to the tools for
writing, compiling, and running programs. You need to make your
own mistakes and learn to correct them. There is no substitute for
writing code. Besides, that’s where the fun is!
There is more to programming – much more – than following a
few rules and reading the manual. This book is not focused on “the
syntax of C++.” C++ is used to illustrate fundamental concepts.
Understanding the fundamental ideals, principles, and techniques is
the essence of a good programmer. Also, “the fundamentals” are
what last: they will still be essential long after today’s programming
languages and tools have evolved or been replaced.
Code can be beautiful as well as useful. This book is written to
help you to understand what it means for code to be beautiful, to
help you to master the principles of creating such code, and to build
up the practical skills to create it. Good luck with programming!
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:
Chapter 1: Computers, People, and Programming
Chapter 11: Customizing Input and Output
Chapter 22: Ideas and History
Chapter 23 Text Manipulation
Chapter 24: Numerics
Chapter 25: Embedded Systems Programming
Chapter 26: Testing
Chapter 27: The C Programming Language
Glossary
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
Notes to the Reader
eiπ + 1
– Leonhard Euler
This chapter is a grab bag of information; it aims to give you an idea of
what to expect from the rest of the book. Please skim through it and read
what you find interesting. Before writing any code, read “PPP support”
(§0.4). A teacher will find most parts immediately useful. If you are
reading this book as a novice, please don’t try to understand everything.
You may want to return and reread this chapter once you feel comfortable
writing and executing small programs.
§0.1 The structure of this book
General approach; Drills, exercises, etc.; What comes after this book?
§0.2 A philosophy of teaching and learning
A note to students; A note to teachers
§0.3 ISO standard C++
Portability; Guarantees; A brief history of C++
§0.4 PPP support
Web resources
§0.5 Author biography
§0.6 Bibliography
0.1 The structure of this book
This book consists of three parts:
Part I (Chapter 1 to Chapter 8) presents the fundamental concepts and
techniques of programming together with the C++ language and library
facilities needed to get started writing code. This includes the type system,
arithmetic operations, control structures, error handling, and the design,
implementation, and use of functions and user-defined types.
Part II (Chapter 9 to Chapter 14) first describes how to get numeric and text
data from the keyboard and from files, and how to produce corresponding
output to the screen and to files. Then, we show how to present numeric data,
text, and geometric shapes as graphical output, and how to get input into a
program from a graphical user interface (GUI). As part of that, we introduce
the fundamental principles and techniques of object-oriented programming.
Part III (Chapter 15 to Chapter 21) focuses on the C++ standard library’s
containers and algorithms framework (often referred to as the STL). We show
how containers (such as vector, list, and map) are implemented and used. In
doing so, we introduce low-level facilities such as pointers, arrays, and dynamic
memory. We also show how to handle errors using exceptions and how to
parameterize our classes and functions using templates. As part of that, we
introduce the fundamental principles and techniques of generic programming.
We also demonstrate the design and use of standard-library algorithms (such
as sort, find, and inner_product).
The order of topics is determined by programming techniques, rather than
programming language features.
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:
CC: concepts and techniques (this paragraph is an example of that)
AA: advice
XX: warning
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.
0.1.1 General approach
In this book, we address you directly. That is simpler and clearer than the
conventional “professional” indirect form of address, as found in most scientific
papers. By “you” we mean “you, the reader,” and by “we” we mean “you, the
author, and teachers,” working together through a problem, as we might have done
had we been in the same room. I use "I" when I refer to my own work or personal
opinions.
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.
0.1.2 Drills, exercises, etc
AA
Programming is not just an intellectual activity, so writing programs is necessary to
master programming skills. We provide three levels of programming practice:
Drills: A drill is a very simple exercise devised to develop practical, almost
mechanical skills. A drill usually consists of a sequence of modifications of a
single program. You should do every drill. A drill is not asking for deep
understanding, cleverness, or initiative. We consider the drills part of the basic
fabric of the book. If you haven’t done the drills, you have not “done” the book.
Exercises: Some exercises are trivial, and others are very hard, but most are
intended to leave some scope for initiative and imagination. If you are serious,
you’ll do quite a few exercises. At least do enough to know which are difficult
for you. Then do a few more of those. That’s how you’ll learn the most. The
exercises are meant to be manageable without exceptional cleverness, rather
than to be tricky puzzles. However, we hope that we have provided exercises
that are hard enough to challenge anybody and enough exercises to exhaust
even the best student’s available time. We do not expect you to do them all,
but feel free to try.
Try this: Some people like to put the book aside and try some examples before
reading to the end of a chapter; others prefer to read ahead to the end before
trying to get code to run. To support readers with the former preference, we
provide simple suggestions for practical work labeled Try this at natural breaks
in the text. A Try this is generally in the nature of a drill but focused narrowly
on the topic that precedes it. If you pass a Try this without trying it out –
maybe because you are not near a computer or you find the text riveting – do
return to it when you do the chapter drill; a Try this either complements the
chapter drill or is a part of it.
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.
0.1.3 What comes after this book?
AA
At the end of this book, will you be an expert at programming and at C++? Of
course not! When done well, programming is a subtle, deep, and highly skilled art
building on a variety of technical skills. You should no more expect to become an
expert at programming in four months than you should expect to become an expert
in biology, in math, in a natural language (such as Chinese, English, or Danish), or
at playing the violin in four months – or in half a year, or a year. What you should
hope for, and what you can expect if you approach this book seriously, is to have a
really good start that allows you to write relatively simple useful programs, to be
able to read more complex programs, and to have a good conceptual and practical
background for further work.
The best follow-up to this initial course is to work on a project developing code
to be used by someone else; preferably guided by an experienced developer. After
that, or (even better) in parallel with a project, read either a professional-level
general textbook, a more specialized book relating to the needs of your project, or a
textbook focusing on a particular aspect of C++ (such as algorithms, graphics,
scientific computation, finance, or games); see §0.6.
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).
0.2 A philosophy of teaching and learning
What are we trying to help you learn? And how are we approaching the process of
teaching? We try to present the minimal concepts, techniques, and tools for you to
do effective practical programs, including
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):
Computers, People, and Programming (PPP2.Ch1)
Ideals and History (PPP2.Ch22)
Text manipulation (incl. Regular expression matching) (PPP2.Ch23)
Numerics (PPP2.Ch24)
Embedded systems programming (PPP2.Ch25)
C-language programming techniques (PPP2.Ch27)
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.
This book teaches both levels. We use the implementation of higher-level
abstractions as our primary examples to introduce low-level language features and
programming techniques. The aim is always to write code at the highest level
affordable, but that often requires a foundation built using lower-level facilities and
techniques. We aim for you to master both levels.
0.2.1 A note to students
AA
Many thousands of first-year university students taught using the first two editions
of this book had never before seen a line of code in their lives. Most succeeded, so
you can do it, too.
You don’t have to read this book as part of a course. The book is widely used for
self-study. However, whether you work your way through as part of a course or
independently, try to work with others. Programming has an – unfair – reputation as
a lonely activity. Most people work better and learn faster when they are part of a
group with a common aim. Learning together and discussing problems with friends
is not cheating! It is the most efficient – as well as most pleasant – way of making
progress. If nothing else, working with friends forces you to articulate your ideas,
which is just about the most efficient way of testing your understanding and making
sure you remember. You don’t actually have to personally discover the answer to
every obscure language and programming environment problem. However, please
don’t cheat yourself by not doing the drills and a fair number of exercises (even if
no teacher forces you to do them). Remember: programming is (among other
things) a practical skill that you must practice to master.
Most students – especially thoughtful good students – face times when they
wonder whether their hard work is worthwhile. When (not if) this happens to you,
take a break, reread this chapter, look at the “Computers, People, and
Programming” and “Ideals and History” chapters posted on the Web (§0.4.1).
There, I try to articulate what I find exciting about programming and why I consider
it a crucial tool for making a positive contribution to the world.
Please don’t be too impatient. Learning any major new and valuable skill takes
time.
The primary aim of this book is to help you to express your ideas in code, not to
teach you how to get those ideas. Along the way, we give many examples of how
we can address a problem, usually through analysis of a problem followed by
gradual refinement of a solution. We consider programming itself a form of problem
solving: only through complete understanding of a problem and its solution can you
express a correct program for it, and only through constructing and testing a
program can you be certain that your understanding is complete. Thus,
programming is inherently part of an effort to gain understanding. However, we aim
to demonstrate this through examples, rather than through “preaching” or
presentation of detailed prescriptions for problem solving.
Exploring the Variety of Random
Documents with Different Content
1808] AN ERROR IN ROUTES 495 for he more than any one
else had been given the chance of trying these roads. But whatever
may be the proportion in which the censure must be distributed, a
certain amount must be reserved for Moore himself. He ought on
first principles to have refused to believe the strange news that was
brought to him. It might have occurred to him to ask how heavy
guns of position had found their way to the ramparts of Almeida, the
second fortress of Portugal, if there was no practicable road leading
to it. A* few minutes spent in consulting any book dealing with
Portuguese history would have shown that in the great wars of the
Spanish Succession, and again in that of 1762 \ forces of all arms
had moved freely up and down the Spanish frontier, in the direction
of Celorica, Guarda, Sabugal, and Castello Branco. Even a glance at
Dumouriez's Account of the Kingdom of Portugal, the one modern
military book on the subject then available, would have enabled
Moore to correct the ignorant reports of the natives. Strangest of all,
there seems to have been no one to tell him that, only four months
before, Loison, in his campaign against the insurgents of Beira, had
taken guns first from Lisbon to Almeida, then from Almeida to Pezo
de Ragoa and Vizeu, and finally from Almeida to Abrantes 2. It is
simply astounding that no one seems to have remembered this
simple fact. In short, it was not easily pardonable in any competent
general that he should accept as possible the statement that there
was no road for artillery connecting the capital of Portugal and the
main stronghold of its north-eastern frontier. Moore did so, and in a
fortnight was bitterly regretting his credulity. 6 If anything adverse
happens,' he wrote to his subordinate Hope, ' I have not necessity to
plead : the road we are now travelling [Abrantes — Villa Velha —
Guarda] is practicable for artillery : the brigade under Wilmot has
already reached Guarda, and as far as I have already seen the road
presents few obstacles, and those easily surmounted. This
knowledge was only acquired by our own officers : when the brigade
was at Castello Branco, it was still not certain that it could
proceed3.'' 1 e.g. in 1706 Lord Galway took over forty guns, twelve
of which were heavy siege-pieces, from Elvas by Alcantara and Coria
to Ciudad Rodrigo. In 1762 the Spaniards took no less than ninety
guns from Ciudad Rodrigo by Celorico and Sabugal to Castello
Branco, and thence back into Spain. 2 Napier does not seem to
know this, and distinctly states (i. 102) that Loison had no guns. 3
Moore to Hope, from Almeida, Nov. 8.
496 MOORE AT SALAMANCA [Nov. 13 What made the case
worse was that another of the three roads, the one by Coimbra and
Celorico, was far easier than that by Guarda. Both Wellesley and
Massena took enormous trains of artillery and baggage over it in
1810, without any particular difficulty1. Misled by the erroneous
reports as to the impracticability of the Portuguese roads, Moore
took the unhappy step of sending six of the seven batteries of his
corps, his only two cavalry regiments, and four battalions of infantry
to act as escort 2, by the circuitous high-road from Elvas to Madrid.
In order to reach Salamanca they were to advance almost to the
gates of the Spanish capital, only turning off at Talavera, in order to
take the route by the Escurial, Espinar, and Arevalo. To show the
result of this lamentable divagation, it is only necessary to remark
that from Lisbon to Salamanca via Coimbra is about 250 miles : from
Lisbon to Salamanca via Elvas, Talavera, and Arevalo is about 380
miles : i. e. it was certain that the column containing all Moore's
cavalry and nearly all his guns would be at least seven or eight days
late at the rendezvous, in a crisis when every moment was of vital
importance. As a matter of fact the head of the main column
reached Salamanca on November 18 : the cavalry and guns turned
up on December 4. It would not be fair, however, to say that the
absence of Hope's column delayed the advance of the whole army
for so much as three weeks. It was only the leading regiments from
Lisbon that appeared on November 13. However carefully the march
of the rest had been arranged, the rear could not have come in till
several days later: indeed the last brigade did not appear till the
twenty-third: this delay, however, was owing to bad arrangements
and preventable accidents. But it cannot be denied that the twelve
days Nov. 23 — Dec. 4 were completely sacrificed by the non-arrival
of the cavalry and guns, without which Moore very wisely refused to
move forward. If the army had been concentrated — Baird could
easily have arrived from Corunna ere this — it would have been able
to advance on November 23, and the campaign would undoubtedly
have been modified 1 In endeavouring to excuse Moore, Napier
takes the strange course of making out that the Guarda road,
though usable, as experience showed, was 'in a military sense, non-
practicable' from its difficulties. This will not stand in face of Moore's
words quoted above. Of the Coimbra — Celorico road he omits all
mention (i. 345). 2 These were the 2nd, 36th, 71st, and 92nd Foot.
1808] STRATEGICAL POSSIBILITIES 497 in its character, for
the Emperor would have learnt of the arrival of Moore upon the
scene some days before he crossed the Somosierra and started on
his march for Madrid. There can be no doubt that he would have
changed his plans on receiving such news, for the sight of a British
army within striking distance would have caused him to turn aside at
once with a large part of his army. Very probably he might have
directed Lefebvre, Victor, and the Imperial Guard — all the
disposable forces under his hand — against Moore, and have left
Madrid alone for the present as a mere secondary object. It is
impossible to deny that disaster to the British arms might have
followed: on the other hand Moore was a cautious general, as his
operations in December showed. He would probably have retired at
once to the mountains, and left the Emperor a fruitless stern-chase,
such as that which actually took place a month later. But whether he
would have fallen back on the route to Portugal, or on the route to
Galicia, it is impossible to say: everything would have depended on
the exact development fcf Napoleon's advance, but the first-named
alternative is the more probable1. 1 Napier has a long note, in
justification of Moore, to the effect that if the concentration point of
the British army had been Burgos instead of Salamanca, Hope's
detour would have cost no waste of time, and would have been
rather profitable than otherwise. But Moore distinctly looked upon
the movement as a deplorable necessity, not as a proper strategical
proceeding. ( It is a great round,' he wrote to Castlereagh on
October 27, when announcing this modification of his original plan, c
and will separate the corps, for a time, from the rest of the army :
but there is no help for it.' Moreover he stated, in this same letter,
that he would not move forward an inch from Salamanca till Hope
should have reached Espinar, on the northern side of the
Guadarrama Pass. At a later date he announced that he should not
advance till Hope had got even nearer to him, and made his way as
far as Arevalo [letter of Nov. 24]. He was too good a general to
dream of a concentration at Burgos, when once he had ascertained
the relative positions of the Spanish and the French armies, for that
place was within a couple of marches of the enemy's outposts at
Miranda and Logroiio. There is, in short, no way of justifying Hope's
circular march, when once it is granted that the roads of Northern
Portugal were not impracticable for artillery. Moore knew this
perfectly well, as his letter to Hope, which we have quoted on p. 495
shows. No arguments are worth anything in his justification when he
himself writes e if anything adverse happens, I have not necessity to
plead.' This is the language of an honest man, conscious that he has
made a mistake, and prepared to take the responsibility. Napier's
apology for him (i. 345-7) is but ingenious and eloquent casuistry.
OMAN, i k k
498 MOORE AT SALAMANCA [Nov. 4 The erroneous
direction given to Moore's cavalry and guns, however, was not the
only reason for the late appearance of the British army upon the
theatre of war. Almost as much delay was caused by a piece of
egregious folly and procrastination, for which the Spaniards were
wholly responsible. When Sir David Baird and the bulk of his great
convoy arrived in the harbour of Corunna on October 13, he was
astonished to find that the Junta of Galicia raised serious objections
to allowing him to land. Their real reason for so doing was that they
wished the British troops to disembark further east, at Gihon or
Santander. They did not realize the military danger of throwing them
ashore in places so close to the French army, nor did it affect them
in the least when they were told that the equipment of Baird's force
in those barren regions would be almost impossible. All that they
cared for was to preserve Galicia from the strain of having to make
provisions for the feeding and transport of a second army, when all
its resources had been sorely tried in supplying (and supplying most
indifferently) the troops of Blake. They did not, however, make
mention of their real objections to Baird's disembarkation in their
correspondence with him, but assumed an attitude of very
suspicious humility, stating that they considered their functions to
have come to an end now that the Central Junta had met, and that
they thought it beyond their competence to give consent to the
landing of such a large body of men without explicit directions from
Aranjuez. Baird could not offer to land by force, in face of this
opposition. He did not, however, move off to Santander (as the
Galicians had hoped), but insisted that an officer should be promptly
dispatched to the Supreme Junta. This was done, but the delay in
receiving an answer was so great that thirteen days were wasted:
the Galician officer bearing the consent of the central government
travelled (so Moore complained) with the greatest deliberation, as if
he were carrying an unimportant message in full time of peace l.
The first regiments, therefore, only landed on October 26, and it was
not till November 4 that all the infantry were ashore. Thus they were
certain to be late at the rendezvous in the plains of Leon. Nor was
this all : the Supreme Junta had suggested that, in order to facilitate
the feeding of the division, Baird should send it forward not in large
masses but in bodies of 2,000 men, with a considerable interval
between them. 1 Moore to Bentinck from Salamanca, Nov. 13, 1808.
1808] BAIRD AT CORUNNA 499 The advice was taken, and
in consequence the troops were soon spread out over the whole
length of road between Corunna and Astorga. The greatest difficulty
was found in equipping them for the march : Galicia, always a poor
country, had been almost stripped of mules and carts to supply
Blake. It was absolutely impossible to procure a sufficient train for
the transport of Baird's food and baggage. He was only able to
gather enough beasts to carry his lighter impedimenta from stage to
stage, by the offer of exorbitant rates of hire. He vainly hoped to
complete his equipment when he should have reached the plains.
Part of his difficulties was caused by lack of money : the
Government at home had not realized that only hard cash would
circulate in Spain : dollars in abundance were to come out in the
Tigre frigate in a few weeks : meanwhile it was expected that the
Spaniards would gladly accept British Government bills. But so little
was paper liked in the Peninsula that only i?5,000 or £6,000 in
dollars could be raised at Corunna 1 : without further resources it
would have been impossible to begin to push the army forward. The
feat was only accomplished by borrowing 92,000 dollars from the
Galician Junta. For this act, carefully ignored by Napier, they deserve
a proper recognition : it shows a much better spirit than might have
been expected after their foolish behaviour about the
disembarkation. Shortly after, Baird succeeded in getting i?40,000
from Mr. Frere, the new minister to Madrid, who chanced to arrive at
Corunna with i?41 0,000 in cash destined for the Spanish
government. Finally on November 9 the expected ship came in with
the 500,000 dollars that had been originally intended to be divided
between Corunna and Lisbon, and Baird had as much money as he
could possibly require, even when mules and draughtoxen had risen
to famine prices in Galicia 2. If he still found it hard to move, it was
because this poor and desolate province was really drained dry of
resources3. 1 Baird to Castlereagh, Oct. 14, 1808. 2 Napier knew the
correspondence of Baird by heart. It is therefore most unfair in him
to suppress the loan made by the Galician Junta, which appears in
Sir David's letters of Oct. 22, 29, and Nov. 13, as also the receipt of
the 500,000 dollars sent by the British Government in the Tigre,
which is acknowledged in the letter of Nov. 9. He implies that the
only sums received were £40,000 from Mr. Frere and £8,000 from Sir
John Moore. The simple fact is that no good act done by a Spanish
Junta or a Tory minister is ever acknowledged by Napier. 3 After
reading Sir Charles Vaughan's diary, showing how hard he and Kk2
500 MOORE AT SALAMANCA [Nov. 13 But what between
the Junta's folly in hindering the landing of the troops, and the
unfortunate lack of money in the second half of October, all-
important time was lost. Baird ought to have been near Salamanca
by November 13 : as a matter of fact he had only reached Astorga
with three brigades of infantry and some artillery, but without a
single mounted man to cover his march, on November 22. There he
received, to his infinite dismay, the news that Blake had been routed
at Espinosa on November 11, and Belvedere at Gamonal on
November 10. There was now no Spanish army between him and
the French : the latter might be advancing, for all he knew, upon
Leon. He heard of Soult being at Reynosa, and Lefebvre at Carrion :
if they continued their advance westward, they would catch him,
with the 9,000 infantry of the Corunna column, marching across
their front on the way to Salamanca. Appalled at the prospect, he
halted at Astorga, and, after sending news of his situation to Moore,
began to prepare to retreat on Corunna, if the marshals should
continue their movement in his direction. This, as we have already
seen, they did not: Napoleon had no knowledge of the position of
the British troops, and instead of ordering the dukes of Dalmatia and
Dantzig to push westward, moved them both in a southerly
direction. Soult came down to Sahagun and Carrion : Lefebvre, on
being relieved by the 2nd Corps, moved on Madrid by way of
Segovia. Thus Baird, left entirely unmolested, was in the end able to
join Moore. It is time to turn to the movements of that general. After
sending off Sir John Hope on his unhappy circular march by Badajoz
and the Escurial, he set out from Lisbon on October 26. He took with
him the whole force in Portugal, save a single division which was left
behind to protect Lisbon, Elvas, and Almeida while a new native
army was being reorganized. This detachment was to be
commanded by Sir John Cradock, who was just due from England: it
comprised four battalions of the German Legion, a battalion each of
the 9th, 27th, 29th, 31st, 40th, 45th, and 97th Foot, the wrecks of
the 20th Light Dragoons, and six batteries of artillery — about 9,000
men in all. The rest, Mr. Stuart found it to procure enough draught
animals to take their small party from Corunna to Madrid, in
September, 1808, I cannot doubt that by October the collecting of
the transport for a whole army was an almost impossible task in
Galicia.
1808] MOORE'S MARCH FROM LISBON 501 twenty-five
battalions of infantry, two cavalry regiments and seven batteries,
marched for Spain. Two brigades under Beresford took the good
road by Coimbra and Celorico to Almeida : three under Fraser went
by Abrantes and Guarda, taking with them the single battery which
Moore had retained with his main body, in order to try whether the
roads of Eastern Portugal were as bad as his advisers had reported.
Two brigades under General Paget, starting from Elvas, not from
Lisbon, separated themselves from Hope and marched on Ciudad
Rodrigo by Alcantara and Coria. The general himself followed in the
track of Fraser, whom he overtook and passed in the neighbourhood
of Castello Branco 1. The march was a most unpleasant one, for the
autumn rains surprised the troops in their passage through the
mountains. Moreover some of the regiments were badly fed, as
Sataro, the Portuguese contractor who had undertaken to supply
them with meat, went bankrupt at this moment and failed to fulfil
his obligations. Nevertheless the advance was carried out with
complete success : the men were in good heart, marched well, and
generally maintained their2 discipline. On November 13 the leading
1 It may perhaps be worth while to give the composition and
brigading of Moore's army on the march from Lisbon and Elvas to
Salamanca. There marched by Coimbra and Almeida, Beresford
[l/9th, 2/43rd, 2/52ndJ and Fane [l/38th, l/79th, 2/95th]. By
Abrantes and Guarda went Bentinck [l/4th, l/28th, l/42nd, and four
companies 5/60th] and Hill [l/5th, l/32nd, l/91st] : this column took
with it one battery : it was followed by two isolated regiments, the
l/6th and l/50th. The corps which marched from Elvas by Alcantara,
under Paget, was composed of the brigades of Alten (1st and 2nd
Light Battalions of the K. G. L.) and Anstruther 20th, l/52nd, l/95th.
The 3rd Regiment joined the army from Almeida, where it was in
garrison, and kthe l/82nd came up late from Lisbon. It was originally
intended that Bentinck and Beresford should form a division under
Fraser, Anstruther and Alten a division under Paget. Of the troops
which reached Salamanca the 3rd and 5/60th were sent back to
Portugal. The original brigading of Baird's force was : — Cavalry
Brigade (Lord Paget) 7th, 10th, and 15th Hussars. 1st Brigade
(Warde) 1st and 3rd batts. of the 1st Foot Guards. 2nd Brigade
(Manningham) 3/lst, l/26th, 2/81st. 3rd Brigade (Leith) 51st, 2/59th,
76th. Light Brigade (R. Crawfurd) 2/43rd, l/95th, 2/95th
(detachments). The 2/14th and 2/23rd were also present, perhaps
as a brigade under Mackenzie. All these arrangements were
temporary, and at Sahagun, as we shall see, the whole army was
recast. A complete table of Moore's army, with its final organization,
force, and losses, will be found in the Appendix. 2 Moore names one
regiment only as an exception.
502 MOORE AT SALAMANCA [Nov. 23 regiments began to
file into Salamanca, whither the Commanderin-chief had already
preceded them. The concentration would have been a little more
rapid but for a strange mistake of General Anstruther, commanding
at Almeida, who detained some of the troops for a few days,
contrary to the orders which had been sent him. But by the twenty-
third the three columns had all joined at Salamanca1, where Moore
now had 15,000 infantry and the solitary battery that had marched
with Eraser's division. The guns had met with some tiresome
obstacles, but had surmounted them with no great difficulty, and
Moore now saw (as we have already shown) that he might have
brought the whole of his artillery with him, if only he had been given
correct information as to the state of the roads. On November 23,
then, the British commander-in-chief lay at Salamanca, with six
infantry brigades and one battery. Baird lay at Astorga, with four
brigades and three batteries : a few of his battalions were still on the
march from Galicia. Hope, with Moore's cavalry and guns, was near
the Escurial. Lord Paget with Baird's equally belated cavalry, which
had left Corunna on the fifteenth, was between Lugo and Astorga.
The situation was deplorable, for it was clear that the army would
require ten days more to concentrate and get into full fighting order,
and it was by no means certain that those ten days would be
granted to it. Such were the unhappy results of the false direction
given to Hope's column, and of the enforced delay of Baird at
Corunna, owing to the folly of the Galician Junta. It may easily be
guessed that Moore's state of mind at this moment was most
unenviable. He had received, much at the same time as did Baird,
the news of Gamonal and Espinosa. He was aware that no screen of
Spanish troops now lay between him and the enemy. He had heard
of the arrival of Milhaud's dragoons at Valladolid, and of Lefebvre's
corps at Carrion, and he expected every moment to hear that they
were marching forward against himself. Yet he could not possibly
advance without cavalry or guns, and if attacked he must fly at once
towards Portugal, for it would be mad to attempt to fight in the
plains with no force at his disposition save a mass of foot-soldiery. If
the French moved forward from Valladolid to Zamora on the one
side, or to Avila on the other, he would inevitably be cut off from
Baird and Hope. 1 Save two stray battalions, which had started last
from Lisbon.
1808] THE DANGERS OF MOORE'S POSITION 503 There
was no serious danger that any one of the three columns might be
caught by the enemy, if they halted at once, for each had a clear
and safe line of retreat, on Lisbon, Corunna, and Talavera
respectively. But if they continued their movement of concentration
the case was otherwise. To any one unacquainted with Bonaparte's
actual design of throwing all his forces on Madrid by the Somosierra
road, it looked not only possible, but probable, that the enemy
would advance westward as well as southward from his present
positions, and if he did so the game was up. The British army, utterly
unable to concentrate, must fly in three separate directions. Moore
and Hope might ultimately unite in front of Lisbon : Baird might he
shipped round from Corunna to the same point. But this movement
would take many weeks, and its moral effect would be deplorable.
What would be thought of the general who marched forward till he
was within eighty miles of the French, and then ordered a precipitate
retreat, without even succeeding in concentrating his army or firing
a single shot? The thought filled Moore's heart with bitterness : must
he, with all his ability and with his well-earned reputation, swell the
list of the failures, and be reckoned with the Duke of York,
Dalrymple, and Hutchinson among the generals who were too late —
who had their chance of fame, and lost it by being an hour, or a
week, or a month behind the decisive moment ? But on one point he
was clear : he must run no unnecessary risk with the forces
committed to him : they were, as was once remarked, not a British
field-army, but the only British field-army. Supposing they were
destroyed, no such second host existed : it would take years to
make another. There were still many regiments on home service, but
those which now lay at Salamanca and Astorga were the pick of the
whole, the corps chosen for foreign service because they were the
fittest for it. The question, then, which Moore had to put to himself
was whether he should persist in attempting to complete the
concentration of his army, and in case of success take an active part
in the campaign, or whether he should simply order each fraction of
the British forces to retreat at once towards some safe base. The
way in which the question should be answered depended mainly on
two points — what would be the movements of the French during
the next few days, and what Spanish troops existed to co-operate
with the British army, in case it were determined to commence
active operations. For clearly the 30,000 men of Moore and Baird
could
504 MOORE AT SALAMANCA [Nov. 23 not hope to struggle
unaided against the whole French army in Spain. To explain Moore's
action, it is necessary to remember that he started with a strong
prejudice against trusting the British army to the mercy of Spanish
co-operation. He had been receiving very gloomy reports both from
Mr. Stuart, the temporary representative of the British Government
at Aranjuez, and from Lord William Bentinck, the military agent
whom Dalrymple had sent to Madrid. The latter was one of the few
British officers who (like Wellesley) foresaw from the first a
catastrophe whenever the French reinforcements should cross the
Ebro K Moreover the character of Moore's correspondence with the
Central Junta, before and during his advance, had conspired with the
reports of Stuart and Bentinck to give him a very unfavourable idea
of the energy and administrative capacity of our allies. He had been
vexed that the Junta refused to put him in direct communication
with the Spanish generals2. He complained that he got from them
tardy, unfrequent, and inaccurate news of the enemy's movements.
He was disgusted that Lopez, the officer sent to aid him in moving
his troops, turned out to know even less about the roads of the
Spanish frontier than he did himself. But above all he professed that
he was terrified by the apathy which he found both among the
officials and the people of the kingdom of Leon and Old Castile. He
had been politely received by the authorities both at Ciudad Rodrigo
and at Salamanca, but he complained that he got little but empty
compliments from them. There was some truth in this allegation,
though certain facts can be quoted against it 3, even from Moore's
own correspondence. 1 There is an undertone of gloom in most of
Bentinck's very capable letters, which contrasts sharply with the very
optimistic views expressed by Doyle and most of the other military
agents. On Oct. 2 he ' feels the danger forcibly ' of the want of a
single commander for the Spanish armies. On Sept. 30 he remarks
that f the Spanish troops consider themselves invincible, but that the
Spanish Government ought not to be deluded by the same opinion.'
On Nov. 14 ehe must not disguise that he thinks very unfavourably
of the affairs of Spain : the Spaniards have not the means to repel
the danger that threatens ' : most of his letters are in more or less
the same strain. 2 Except with Castanos, from whom some sensible
but rather vague advice was procured. 3 e.g. in his letter of Nov. 19
Moore speaks of the town of Salamanca as doing its best for him :
the clergy were exerting themselves, and a convent
1808] MOORE AND THE SPANIARDS 505 Leon and Old
Castile had, as we have already had occasion to remark, been far
less energetic than other parts of the Peninsula in raising new troops
and coming forward with contributions to the national exchequer.
They had done no more than furnish the 10,000 men of Cuesta's
disorderly 'Army of Castile,'' a contingent utterly out of proportion
with their population and resources. Nor did they seem to realize the
scandal of their own sloth and procrastination. Moore had expected
to see every town full of new levies undergoing drill before marching
to the Ebro, to discover magazines accumulated in important places
like Ciudad Rodrigo and Salamanca, to find the military and civil
officials working busily for the armies at the front. Instead he found
an unaccountable apathy. Even after the reports of Espinosa and
Gamonal had come to hand, the jDeople and the authorities alike
seemed to be living in a sort of fools1 paradise, disbelieving the
gloomy news that arrived, or at least refusing to recognize that the
war was now at their own doors. Moore feared that this came from
want of patriotism or of courage. As a matter of fact, the people's
hearts were sound enough1, but they had still got ' Baylen on the
brain ' : they simply failed to of nuns had promised him £5,000. In
his Journal he has a testimonial to the fidelity with which the people
of Tordesillas protected an English officer from a raiding- party of
French cavalry. There are some similar notes in British memoirs :
e.g. ' T. S.' of the 71st expresses much gratitude for the kindness of
the people of Peiiaranda, who, when Hope's division arrived in a
drenched and frozen condition, rolled out barrels of spirits into the
streets and gave every man a good dram before the regiments
marched on. Some towns, e. g. Zamora and Alba de Tormes,
behaved well in opposing (though without any hope of success) the
French, when they did appear. 1 As to the conduct of the Spaniards I
think that the best commentary on it is that of Leith Hay (i. 80-1),
who was riding all over Castile and Leon in these unhappy weeks. (
Thus terminated a journey of about 900 miles, in which a
considerable portion of the country had been traversed, under
circumstances which enabled me to ascertain the sincere feeling of
the people. It is but justice to say that I met with but one sentiment
as to the war : that I was everywhere treated with kindness. I
mention this as a creditable circumstance to the inhabitants of the
Peninsula, and in contradiction to the statements often recorded,
unjustly in my opinion, as to the want of faith, supineness, and
perfidy of the Spanish people. . . . Their conduct was throughout
distinguished by good faith, if it was at the same time rendered
apparently equivocal from characteristic negligence, want of energy,
and the deficiency of that moral power that can alone be derived
from free institutions and an enlightened aristocracy.'
506 MOORE AT SALAMANCA [Nov. 27 recognize the full
horror of the situation. That their armies were not merely beaten but
dispersed, that the way to Madrid was open to Bonaparte, escaped
them. This attitude of mind enraged Moore. * In these provinces,1
he wrote, ' no armed force whatever exists, either for immediate
protection or to reinforce the armies. The French cavalry from
Burgos, in small detachments, are overrunning the province of Leon,
and raising contributions to which the inhabitants submit without the
least resistance : the enthusiasm of which we heard so much
nowhere appears. Whatever good-will there is (and among the lower
orders I believe there is a good deal) is taken no advantage of. I am
at this moment in no communication with any of their generals. I am
ignorant of their plans, or those of their government V And again, he
adds in despair, ' I hope a better spirit exists in the southern
provinces : here no one stirs — and yet they are well inclined2.1
While Leon and Old Castile were in this state of apathy, it was
maddening to Moore to receive constant appeals from the Supreme
Junta, begging that the British army might move forward at once.
Their dispatches were accompanied by representations, which Moore
knew to be inaccurate, concerning the numbers and enthusiasm of
the Spanish armies still in the field, and by misrepresentations of the
force of the French. They were also backed by urgent letters from
Mr. Frere, the new ambassador at Madrid, urging him to give help at
all costs. These appeals were intolerable to a man who dared not
advance because his army (partly by his own fault, partly owing to
circumstances that had not been under his control) was not
concentrated. From the point of view of policy, Moore knew that it
was all-important that he should take the field : but, from the point
of view of strategy, he saw that an advance with the 15,000 men
that he had at Salamanca might very probably lead to instant and
complete disaster. He refused to move, but all the time he knew that
his refusal was having the worst effect, and would certainly be
represented by his critics as the result of timidity and selfishness. It
was this consciousness that caused him to fill his dispatches with the
bitterest comments on the Spanish government and people. He had
been induced to advance to Salamanca, he said, by false pretences.
He had been told that there was a large army in front of him, ready
to cover his concentration. He had been informed 1 Moore to
Castlereagh from Salamanca, Nov. 24. 2 Ibid., Dec. 8.
1808] MOORE CONTEMPLATES RETREAT 507 that the
whole country-side was full of enthusiasm, that he might look for
ready help from every official, that when once he had crossed the
frontier transport and food would be readily provided for him.
Instead, he found nothing but apathy and disasters. 'Had the real
strength and composition of the Spanish armies been known, and
the defenceless state of the country, I conceive that Cadiz, not
Corunna, would have been chosen for the disembarkation of the
troops from England : and Seville or Cordova, not Salamanca, would
have been selected as the proper place for the assembling of this
army V Thus he wrote to Castlereagh : to Frere, in response to
constant invitations to strike a blow of some sort in behalf of Spain,
he replied in more vigorous terms2. 'Madrid is threatened; the
French have destroyed one army (Blake's), have passed the Ebro,
and are advancing in superior numbers against another (Castanos'),
which from its composition promises no resistance, but must retire
or be overwhelmed. No other armed force exists in this country : I
perceive no enthusiasm or determined spirit among the people. This
is a state of affairs quite different from that conceived by the British
Government, when they determined to send troops to the assistance
of Spain. It was not expected that these were to cope alone with the
whole force of France : as auxiliaries they were to aid a people who
were believed to be enthusiastic, determined, and prepared for
resistance. It becomes therefore a question whether the British army
should remain to be attacked in its turn, or should retire from a
country where the contest, from whatever circumstances, is become
unequal.' All that Moore wrote was true : yet, granting the accuracy
of every premise, his conclusion that he ought to retire to Portugal
was not necessarily correct. The British Government had
undoubtedly over-estimated the power and resources of Spain : the
Supreme Junta had shown no capacity for organization or command
: most of the Spanish generals had committed gross military
blunders. But none of these facts were enough to justify Moore in
washing his hands of the whole business, and marching out of Spain
without firing a shot. He had not been sent to help the patriots only
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
textbookfull.com