0% found this document useful (0 votes)
23 views

Programming Abstractions In C Eric Roberts pdf download

The document is a comprehensive overview of the textbook 'Programming Abstractions in C' by Eric Roberts, which has been revised to align closely with industry practices in C++. It includes a detailed table of contents covering various topics in C++ programming, such as functions, strings, recursion, and data structures. The text aims to serve as both a tutorial and a reference for students in computer science courses at Stanford University.

Uploaded by

mattyychonr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Programming Abstractions In C Eric Roberts pdf download

The document is a comprehensive overview of the textbook 'Programming Abstractions in C' by Eric Roberts, which has been revised to align closely with industry practices in C++. It includes a detailed table of contents covering various topics in C++ programming, such as functions, strings, recursion, and data structures. The text aims to serve as both a tutorial and a reference for students in computer science courses at Stanford University.

Uploaded by

mattyychonr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Programming Abstractions In C Eric Roberts

download

https://ebookbell.com/product/programming-abstractions-in-c-eric-
roberts-5903396

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Programming Abstractions In C Itebooks

https://ebookbell.com/product/programming-abstractions-in-c-
itebooks-23837786

Programming Abstraction In C 1st Edition Eric Roberts

https://ebookbell.com/product/programming-abstraction-in-c-1st-
edition-eric-roberts-5556274

Programming Problem Solving Abstraction With C Rev Ed Moffat

https://ebookbell.com/product/programming-problem-solving-abstraction-
with-c-rev-ed-moffat-6694568

Abstracting Away The Machine The History Of The Fortran Programming


Language Formula Translation Lorenzo

https://ebookbell.com/product/abstracting-away-the-machine-the-
history-of-the-fortran-programming-language-formula-translation-
lorenzo-26481178
Programming Languages And Systems 31st European Symposium On
Programming Esop 2022 Held As Part Of The European Joint Conferences
On Theory And Practice Of Software Etaps 2022 Munich Germany April 27
2022 Proceedings Ilya Sergey
https://ebookbell.com/product/programming-languages-and-systems-31st-
european-symposium-on-programming-esop-2022-held-as-part-of-the-
european-joint-conferences-on-theory-and-practice-of-software-
etaps-2022-munich-germany-april-27-2022-proceedings-ilya-
sergey-44887738

Programming 101 Learn To Code Using The Processing Programming


Language 2nd Edition 2nd Jeanine Meyer

https://ebookbell.com/product/programming-101-learn-to-code-using-the-
processing-programming-language-2nd-edition-2nd-jeanine-meyer-46238180

Programming 101 The How And Why Of Programming Revealed Using The
Processing Programming Language Jeanine Meyer

https://ebookbell.com/product/programming-101-the-how-and-why-of-
programming-revealed-using-the-processing-programming-language-
jeanine-meyer-46318424

Programming And Gui Fundamentals Tcltk For Electronic Design


Automation Suman Lata Tripathi

https://ebookbell.com/product/programming-and-gui-fundamentals-tcltk-
for-electronic-design-automation-suman-lata-tripathi-46318712

Programming With Openscad A Beginners Guide To Coding 3dprintable


Objects 1st Edition Justin Gohde

https://ebookbell.com/product/programming-with-openscad-a-beginners-
guide-to-coding-3dprintable-objects-1st-edition-justin-gohde-46410140
Programming
Abstractions in
C ++

Eric S. Roberts
Stanford University
Spring Quarter 2012
Foreword
This text represents a major revision of the course reader that we’ve been using at
Stanford for the last several years. The primary goal of the revision was to bring the
approach more closely in line with the way C++ is used in industry, which will in
turn make it easier to export Stanford’s approach to teaching data structures to a
larger fraction of schools. Even though this quarter’s draft is reasonably complete,
the text remains somewhat rough. In particular, these chapters have not yet had the
benefit of the wonderful copyediting service that my wife Lauren Rusk has provided
for all my books.

This textbook has had an interesting evolutionary history that in some ways
mirrors the genesis of the C++ language itself. Just as Bjarne Stroustrup’s first
version of C++ was implemented on top of a C language base, this reader began its
life as my textbook Programming Abstractions in C (Addison-Wesley, 1998). In
2002-03, Julie Zelenski updated it for use with the C++ programming language,
which we began using in CS106 B and CS106 X during that year. Although the
revised text worked fairly well at the outset, CS106 B and CS106 X have evolved in
recent years so that their structure no longer tracks the organization of the book. In
2009, I embarked on a comprehensive process of rewriting the book so that students
in these courses can use it as both a tutorial and a reference. As always, that process
takes a considerable amount of time, and there are almost certainly some sections of
the book that need a substantial rewrite.

I want to thank my colleagues at Stanford over the last several years, starting
with Julie Zelenski for her extensive work on the initial C++ revision. My
colleagues Keith Schwarz, Jerry Cain, Stephen Cooper, and Mehran Sahami have
all made important contributions to the revision. I also need to express my thanks to
several generations of section leaders and so many students over the years, all of
whom have helped make it so exciting to teach this wonderful material. Finally, I
want to thank the students in CS106 B in winter quarter 2011-12 who put up with a
partially finished reader and contributed many error reports and suggestions.

I’ve always believed that programming is one of the most challenging and
exciting intellectual activities that humans have ever discovered. By staying close
to the machine, C++ gives you all the freedom you need to build applications that
take advantage of the full power of modern computing. I hope you all enjoy the
ride.

i
Contents
1 Overview of C++ 1
1.1 Your first C++ program 2
1.2 The history of C++ 3
1.3 The structure of a C++ program 6
1.4 Variables 14
1.5 Data types 19
1.6 Expressions 26
1.7 Statements 36
1.8 The Stanford C++ libraries 48
Summary 49
Review questions 50
Exercises 52

2 Functions and Libraries 57


2.1 The idea of a function 58
2.2 Libraries 61
2.3 Defining functions in C++ 63
2.4 The mechanics of function calls 67
2.5 Reference parameters 75
2.6 Interfaces and implementations 80
2.7 Principles of interface design 87
2.8 Designing a random number library 92
2.9 A brief tour of the graphics library 110
Summary 113
Review questions 114
Exercises 116

3 Strings 125
3.1 Using strings as abstract values 126
3.2 String operations 129
3.3 The <cctype> library 137
3.4 Modifying the contents of a string 138
3.5 The legacy of C-style strings 139
3.6 Writing string applications 140
3.7 The strlib.h library 146
Summary 147
Review questions 148
Exercises 149

ii
4 Streams 159
4.1 Using strings as abstract values 160
4.2 Formatted input 165
4.3 Data files 167
4.4 Class hierarchies 180
4.5 Exploring the Stanford libraries 187
Summary 189
Review questions 190
Exercises 191

5 Collections 197
5.1 The Vector class 199
5.2 The Stack class 213
5.3 The Queue class 219
5.4 The Map class 228
5.5 The Set class 234
5.6 Iterating over a collection 238
Summary 245
Review questions 247
Exercises 248

6 Designing Classes 263


6.1 Representing points 264
6.2 Operator overloading 273
6.3 Rational numbers 284
6.4 Designing a token scanner class 295
6.5 Encapsulating programs as classes 305
Summary 307
Review questions 308
Exercises 310

iii
7 Introduction to Recursion 319
7.1 A simple example of recursion 320
7.2 The factorial function 322
7.3 The Fibonacci function 329
7.4 Checking palindromes 336
7.5 The binary search algorithm 339
7.6 Mutual recursion 340
7.7 Thinking recursively 342
Summary 344
Review questions 346
Exercises 348

8 Recursive Strategies 353


8.1 The Towers of Hanoi 354
8.2 The subset-sum problem 365
8.3 Generating permutations 368
8.4 Graphical recursion 372
Summary 379
Review questions 379
Exercises 380

9 Backtracking Algorithms 393


9.1 Recursive backtracking in a maze 394
9.2 Backtracking and games 404
9.3 The minimax algorithm 413
Summary 419
Review questions 420
Exercises 421

10 Algorithmic Analysis 433


10.1 The sorting problem 434
10.2 Computational complexity 439
10.3 Recursion to the rescue 447
10.4 Standard complexity classes 453
10.5 The Quicksort algorithm 456
10.6 Mathematical induction 462
Summary 466
Review questions 467
Exercises 470

iv
11 Pointers and Arrays 477
11.1 The structure of memory 478
11.2 Pointers 488
11.3 Arrays 498
11.4 Using functions as data values 508
Summary 515
Review questions 517
Exercises 520

12 Dynamic Memory Management 527


12.1 Dynamic allocation and the heap 528
12.2 Defining a CharStack class 533
12.3 Heap-stack diagrams 544
12.4 Copying objects 550
Summary 556
Review questions 557
Exercises 559

13 Efficiency and Representation 563


13.1 The concept of an editor buffer 564
13.2 Defining the buffer abstraction 566
13.3 An array-based implementation 570
13.4 A stack-based implementation 578
13.5 A list-based implementation 583
Summary 601
Review questions 602
Exercises 604

14 Linear Structures 611


14.1 Templates 612
14.2 Defining stacks as a template class 615
14.3 Implementing stacks as linked lists 622
14.4 Implementing queues 626
14.5 Implementing vectors 640
Summary 648
Review questions 649
Exercises 650

v
15 Maps and Hashing 653
15.1 Implementing maps using arrays 654
15.2 Lookup tables 660
15.3 Hashing 663
Summary 675
Review questions 675
Exercises 677

16 Trees 681
16.1 Family trees 683
16.2 Binary search trees 685
16.3 Balanced trees 698
16.4 Implementing maps using BSTs 709
Summary 711
Review questions 712
Exercises 715

17 Expression Trees 725


17.1 Overview of the interpreter 726
17.2 The structure of expressions 731
17.3 Defining the expression hierarchy 736
17.4 Parsing an expression 750
Summary 756
Review questions 757
Exercises 759

18 Sets 765
18.1 Sets as a mathematical abstraction 766
18.2 Expanding the set interface 770
18.3 Implementation strategies for sets 778
18.4 Optimizing sets of small integers 780
Summary 786
Review questions 787
Exercises 790

vi
19 Graphs 793
19.1 The structure of a graph 794
19.2 Representation strategies 798
19.3 A low-level graph abstraction 802
19.4 Graph traversals 809
19.5 Defining a Graph class 815
19.6 Finding shortest paths 824
19.7 Implementing priority queues 828
Summary 831
Review questions 833
Exercises 835

vii
A Library Interfaces 847
A-1 cmpfn.h 848
A-2 console.h 849
A-3 direction.h 850
A-4 error.h 852
A-5 filelib.h 853
A-6 foreach.h 859
A-7 gevents.h 860
A-8 graph.h 874
A-9 graphics.h 879
A-10 grid.h 887
A-11 gtypes.h 890
A-12 gwindow.h 895
A-13 hashmap.h 904
A-14 hashset.h 907
A-15 lexicon.h 913
A-16 map.h 916
A-17 point.h 919
A-18 pqueue.h 921
A-19 queue.h 924
A-20 random.h 927
A-21 set.h 928
A-22 simpio.h 933
A-23 sound.h 934
A-24 stack.h 936
A-25 strlib.h 938
A-26 thread.h 941
A-27 tokenscanner.h 945
A-28 vector.h 951

Index 955

viii
Chapter 1
An Overview of C++

Out of these various experiments come programs. This is our


experience: programs do not come out of the minds of one person
or two people such as ourselves, but out of day-to-day work.
— Stokely Carmichael and Charles V. Hamilton,
Black Power, 1967
2 Overview of C++

In Lewis Carroll’s Alice’s Adventures in Wonderland, the King asks the White
Rabbit to “begin at the beginning and go on till you come to the end: then stop.”
Good advice, but only if you’re starting from the beginning. This book is designed
for a second course in computer science and therefore assumes that you have
already begun your study of programming. At the same time, because first courses
vary considerably in what they cover, it is difficult to rely on any specific material.
Some of you, for example, will already understand C++ control structures from
prior experience with closely related languages such as C or Java. For others,
however, the structure of C++ will seem unfamiliar. Because of this disparity in
background, the best approach is to adopt the King’s advice. This chapter therefore
“begins at the beginning” and introduces you to those parts of the C++ language
you will need to write simple programs.

1.1 Your first C++ program


As you will learn in more detail in the following section, C++ is an extension of an
extremely successful programming language called C, which appeared in the early
1970s. In the book that serves as C’s defining document, The C Programming
Language, Brian Kernighan and Dennis Ritchie offer the following advice on the
first page of Chapter 1.

The only way to learn a new programming language is by


writing programs in it. The first program to write is the same
for all languages:
Print the words
hello, world
This is the big hurdle; to leap over it you have to be able to
create the program text somewhere, compile it successfully,
load it, run it, and find out where the output went. With these
mechanical details mastered, everything else is comparatively
easy.

If you were to rewrite it in C++, the “Hello World” program would end up looking
something like the code in Figure 1-1.

At this point, the important thing is not to understand exactly what all of the
lines in this program mean. There is plenty of time to master those details later.
Your mission—and you should decide to accept it—is to get the HelloWorld
program running. Type in the program exactly as it appears in Figure 1-1 and then
figure out what you need to do to make it work. The exact steps you need to use
depend on the programming environment you’re using to create and run C++
programs. If you are using this textbook for a class, your instructor will presumably
provide some reference material on the programming environments you are
1.1 Your first C++ program 3

F I G U R E 1 - 1 The “Hello World” program

/*
* File: HelloWorld.cpp
* --------------------
* This file is adapted from the example
* on page 1 of Kernighan and Ritchie's
* book The C Programming Language.
*/

#include <iostream>
using namespace std;

int main() {
cout << "hello, world" << endl;
return 0;
}

expected to use. If you are reading this book on your own, you’ll need to refer to
the documentation that comes with whatever programming environment you’re
using for C++.

When you get all of these details worked out, you should see the output from the
HelloWorld program on a window somewhere on your computer screen. On the
Apple Macintosh on which I prepared this book, that window looks like this:

HelloWorld
hello, world

On your computer, the window will probably have a somewhat different appearance
and may include additional status messages along with your program’s cheery
“hello, world” greeting. But the message will be there. And although it may not be
true that “everything else is comparatively easy” as Kernighan and Ritchie suggest,
you will have achieved a significant milestone.

1.2 The history of C++


In the early days of computing, programs were written in machine language, which
consists of the primitive instructions that can be executed directly by the machine.
Programs written in machine language are difficult to understand, mostly because
the structure of machine language reflects the design of the hardware rather than the
needs of programmers. Worse still, each type of computing hardware has its own
4 Overview of C++

machine language, which means that a program written for one machine will not run
on other types of hardware.

In the mid-1950s, a group of programmers under the direction of John Backus at


IBM had an idea that profoundly changed the nature of computing. Would it be
possible, Backus and his colleagues wondered, to write programs that resembled the
mathematical formulas they were trying to compute and have the computer itself
translate those formulas into machine language? In 1955, this team produced the
initial version of FORTRAN (whose name is a contraction of formula translation),
which was the first example of a higher-level programming language.

Since that time, many new programming languages have been invented, most of
which build on previous languages in an evolutionary way. C++ represents the
joining of two branches in that evolution. One of its ancestors is a language called
C, which was designed at Bell Laboratories by Dennis Ritchie in 1972 and then
later revised and standardized by the American National Standards Institute (ANSI)
in 1989. But C++ also descends from a family of languages designed to support a
different style of programming that has dramatically changed the nature of software
development in recent years.

The object-oriented paradigm


Over the last two decades, computer science and programming have gone through
something of a revolution. Like most revolutions—whether political upheavals or
the conceptual restructurings that Thomas Kuhn describes in his 1962 book The
Structure of Scientific Revolutions—this change has been driven by the emergence
of an idea that challenges an existing orthodoxy. Initially, the two ideas compete,
and, at least for a while, the old order maintains its dominance. Over time,
however, the strength and popularity of the new idea grows, until it begins to
displace the older idea in what Kuhn calls a paradigm shift. In programming, the
old order is represented by the procedural paradigm, in which programs consist of
a collection of procedures and functions that operate on data. The new model is
called the object-oriented paradigm, in which programs are viewed instead as a
collection of data objects that embody particular characteristics and behavior.

The idea of object-oriented programming is not really all that new. The first
object-oriented language was SIMULA, a language for coding simulations designed
by the Scandinavian computer scientists Ole-Johan Dahl and Kristen Nygaard in
1967. With a design that was far ahead of its time, SIMULA anticipated many of
the concepts that later became commonplace in programming, including the concept
of abstract data types and much of the modern object-oriented paradigm. In fact,
much of the terminology used to describe object-oriented languages comes from the
original 1967 report on SIMULA.
1.2 The history of C++ 5

Unfortunately, SIMULA did not generate a great deal of interest in the years
after its introduction. The first object-oriented language to gain any significant
following within the computing profession was Smalltalk, which was developed at
the Xerox Palo Alto Research Center in the late 1970s. The purpose of Smalltalk,
which is described in the book Smalltalk-80: The Language and Its Implementation
by Adele Goldberg and David Robson, was to make programming accessible to a
wider audience. As such, Smalltalk was part of a larger effort at Xerox PARC that
gave rise to much of the modern user-interface technology that is now standard on
personal computers.

Despite many attractive features and a highly interactive user environment that
simplifies the programming process, Smalltalk never achieved much commercial
success. The profession as a whole took an interest in object-oriented programming
only when the central ideas were incorporated into variants of C, which had already
become an industry standard. Although there were several parallel efforts to design
an object-oriented language based on C, the most successful was the language C++,
which was developed by Bjarne Stroustrup at AT&T Bell Laboratories in the early
1980s. C++ includes standard C as a subset, which makes it possible to integrate
C++ code into existing C programs in a gradual, evolutionary way.

Although object-oriented languages have gained some of their popularity at the


expense of procedural ones, it would be a mistake to regard the object-oriented and
procedural paradigms as mutually exclusive. Programming paradigms are not so
much competitive as they are complementary. The object-oriented and the
procedural paradigm—along with other important paradigms such as the functional
programming style embodied in LISP—all have important applications in practice.
Even within the context of a single application, you are likely to find a use for more
than one approach. As a programmer, you must master many different paradigms,
so that you can use the conceptual model that is most appropriate to the task at
hand.

The compilation process


When you write a program in C++, your first step is to create a file that contains the
text of the program, which is called a source file. Before you can run your
program, you need to translate the source file into an executable form. The first
step in that process is to invoke a program called a compiler, which translates the
source file into an object file containing the corresponding machine-language
instructions. This object file is then combined with other object files to produce an
executable file that can be run on the system. The other object files typically
include predefined object files called libraries that contain the machine-language
instructions for various operations commonly required by programs. The process of
6 Overview of C++

combining all the individual object files into an executable file is called linking.
The steps in the compilation process are illustrated in Figure 1-2.

As noted in the discussion of the HelloWorld program earlier in this chapter,


the specific details of the compilation process vary from one machine to another.
There is no way that a general textbook like this can tell you exactly what
commands you should use to run a program on your system. The good news is that
the C++ programs themselves will look the same. One of the advantages of
programming in a higher-level language like C++ is that doing so allows you to
ignore the particular characteristics of the hardware and create programs that will
run on many different machines.

1.3 The structure of a C++ program


The best way to get a feeling for the C++ programming language is to look at some
sample programs, even before you understand the details of the language. The
HelloWorld program is a start, but it is so simple that it doesn’t include many of
the features you’d expect to see in a program. Since this book is designed for a
second course in computer science, you’ve almost certainly written programs that
read input from the user, store values in variables, use loops to perform repeated
calculations, and make use of subsidiary functions to simplify the structure of the

F I G U R E 1 - 2 The compilation process

source file object file


/* 10011111111000111100111011110100111101100
* File: HelloWorld.cpp 11010011011100101110111000111001111010100
* -------------------- 11100000010000111000000110111110001010111
* This file is adapted from the example 10001010111010010001000110011011100010010
* on page 1 of Kernighan and Ritchie’s 11000100101011101001011011000101101111101
* book The C Programming Language. 10110111110111011111101100110110111001110
*/ 11100111000111111101000111110001110111010
11110011111010111101110100001111011101010
using namespace std; 11011101000011111101010011100101111011111
#include <iostream> 10111101111101011101111110100010101000000
11011110011011101000011100011111001010010
int main() { 10101000011110011100101000100110111010111
cout << "hello, world" << endl; 10110101110111011101011110001001111110010
return 0; 11111111110011111100100111011011010000100
}
compiler 11010111001111110001101010010111101000010

executable file
10011111111000111100111011110100111101100
11010011011100101110111000111001111010100
11100000010000111000000110111110001010111
10001010111010010001000110011011100010010
11000100101011101001011011000101101111101
10110111110111011111101100110110111001110
11100111000111111101000111110001110111010
11110011111010111101110100001111011101010
11011101000011111101010011100101111011111
10111101111101011101111110100010101000000
11011110011011101000011100011111001010010
10101000011110011100101000100110111010111
10110101110111011101011110001001111110010
11111111110011111100100111011011010000100

linker 11010111001111110001101010010111101000010
10001100111001011101000000111110110100000
10111011111101011111111101001110100000111
10100111101011001110101100000101111010000

library file 10010011011000111011010100010000110101101


10111010110111010111010110111011111110001
11000010011100111110010000100000101110110
10001100011111101010111000101011101011100
10001100111001011101000000111110110100000 11010011011100101011010001001111100000110
10111011111101011111111101001110100000111 11111110111001111000001001010010000100100
10100111101011001110101100000101111010000 11000111110110110000101100110011010010100
10010011011000111011010100010000110101101 10011111010010011100010101000010010010111
10111010110111010111010110111011111110001 11111000000000101100110101111111011010100
11000010011100111110010000100000101110110 10100000011000001100001000001101111000011
10001100011111101010111000101011101011100 10101101110001001010110111000100110010111
11010011011100101011010001001111100000110 11010101111011111111011110011100111101001
11111110111001111000001001010010000100100
11000111110110110000101100110011010010100
10011111010010011100010101000010010010111
11111000000000101100110101111111011010100
10100000011000001100001000001101111000011
10101101110001001010110111000100110010111
11010101111011111111011110011100111101001
1.3 The structure of a C++ program 7

program. The HelloWorld program does none of these things. To illustrate more
of the features of C++, Figure 1-3 shows the code for a program that lists powers of
two along with some annotations that describe the various parts of the program.

F I G U R E 1 - 3 The structure of a C++ program

/*
* File: PowersOfTwo.cpp
* ---------------------
* This program generates a list of the powers of Program comments
* two up to an exponent limit entered by the user.
*/

#include <iostream> Library inclusions


using namespace std;
/* Function prototypes */
int raiseToPower(int n, int k); Function prototype
/* Main program */
int main() {
int limit;
cout << "This program lists powers of two." << endl;
cout << "Enter exponent limit: ";
cin >> limit;
for (int i = 0; i <= limit; i++) { Main program
cout << "2 to the " << i << " = "
<< raiseToPower(2, i) << endl;
}
return 0;
}
/*
* Function: raiseToPower
* Usage: int p = raiseToPower(n, k); Function comment
* ----------------------------------
* Returns the integer n raised to the kth power.
*/
int raiseToPower(int n, int k) {
int result = 1;
for (int i = 0; i < k; i++) {
result *= n; Function definition
}
return result;
}
8 Overview of C++

When you run the PowersOfTwo program shown in Figure 1-3, the computer
begins by asking you for an exponent limit, which specifies how many powers of
two the program should generate. If you type in 8, for example, the program will
generate a list of the powers of two up to 28, as follows:

PowersOfTwo
This program lists powers of two.
Enter exponent limit: 8
2 to the 0 = 1
2 to the 1 = 2
2 to the 2 = 4
2 to the 3 = 8
2 to the 4 = 16
2 to the 5 = 32
2 to the 6 = 64
2 to the 7 = 128
2 to the 8 = 256

This screen image shows what happens if you execute the PowersOfTwo program.
Such images are called sample runs. In each sample run, input from the user
appears in blue so that it is easy to distinguish input data from the output generated
by the program.

As the annotations in Figure 1-3 indicate, the PowersOfTwo program is divided


into several components, which are discussed in the next few sections.

Comments
Much of the text in Figure 1-3 consists of English-language comments. A comment
is text that is ignored by the compiler but which nonetheless conveys information to
other programmers. A comment consists of text enclosed between the markers
/* and */ and may continue over several lines. Alternatively, you can also specify
single-line comments, which begin with the characters // and extend through the
end of the line. This book uses the multiline /* . . . */ comment form except when
the comment marks some part of a program that is not yet complete. Adopting that
strategy makes it easier to find unfinished parts of a program.

Modern programming environments typically use colors to make it easier to


distinguish the various parts of a program. On a color monitor, it is easy to display
many colors, so that a programming environment might, for example, display
keywords in one color, strings in another, and comments in yet some other shade.
Because this text is typeset using only two colors, program listings must be more
economical in their use of color. The only visual distinction that survives the
restricted color palette is between comments, which appear in blue, and the code
actually executed by the computer, which appears in black.
1.3 The structure of a C++ program 9

As you can see from Figure 1-3, the PowersOfTwo program includes a comment
at the beginning that describes the program as a whole and one before the definition
of raiseToPower that describes the operation of that function at a lower level of
detail. In addition, the program includes a couple of one-line comments that act like
section headings in English text.

Library inclusions
Modern programs are never written without using libraries, which are collections of
previously written tools that perform useful operations. C++ defines a number of
standard libraries, of which one of the most important is iostream. This library
defines a set of simple input and output operations based on a data structure called a
stream, which is a data structure used to manage the flow of information to or from
some data source, such as the console or a file.

To gain access to the iostream library, your program must contain the line

#include <iostream>

This line instructs the C++ compiler to read the relevant definitions from what is
called a header file. The angle brackets in this line indicate that the header file is a
system library that is part of standard C++. Beginning in Chapter 2, you will also
have occasion to use header files that you have written yourself or that come from
other libraries. Those header files typically end with the suffix .h and are enclosed
in quotation marks instead of angle brackets.

In C++, reading in a header file using #include is often not sufficient by itself
to use a system library. To ensure that the names defined in different parts of a
large system do not interfere with one another, the designers of C++ made it
possible to segment code into structures called namespaces, each of which keeps
track of its own set of names. The standard C++ libraries use a namespace called
std, which means that you cannot refer to the names defined in standard header
files like iostream unless you let the compiler know to which namespace those
definitions belong.

Increasingly, professional C++ programmers specify the namespace explicitly by


adding the prefix std:: before each name to which it applies. Using this approach,
the first line of the HelloWorld program becomes

std::cout << "hello, world" << std::endl;

If you want to write code that looks like that of a professional, you can adopt this
style. For someone just learning the language, all those std:: tags make programs
harder to read, so this book instead adopts the convention of adding the line

using namespace std;


10 Overview of C++

at the end of the library inclusion section. At times—most importantly when you
start to define your own library interfaces in Chapter 2—you will need to remember
that the complete name of anything in the standard library namespace includes the
std:: prefix. For the moment, however, it is probably easiest to think of the

using namespace std;

as one of the incantations that the C++ compiler requires to work its magic on your
code.

Function prototypes
Computation in a C++ program is carried out in the context of functions. A
function is a named section of code that performs a specific operation. The
PowersOfTwo program contains two functions—main and raiseToPower—each
of which is described in more detail in one of the sections that follow. Although the
definitions of these functions appear toward the end of the file, the PowersOfTwo
program provides a concise description of the raiseToPower function just after the
library inclusions. This concise form is called a prototype and makes it possible to
make calls to that function before its actual definition appears.

A C++ prototype consists of the first line of the function definition followed by a
semicolon, as illustrated by the prototype

int raiseToPower(int n, int k);

This prototype tells the compiler everything it needs to know about how to call that
function when it appears in the code. As you will see in the expanded discussion of
functions in Chapter 2, the prototype for raiseToPower indicates that the function
takes two integers as arguments and returns an integer as its result.

You must provide the declaration or definition of each function before making
any calls to that function. C++ requires such prototype declarations so the compiler
can check whether calls to functions are compatible with the function definitions. If
you accidentally supply the wrong number of arguments or if the arguments are of
the wrong type, the compiler reports an error, which makes it easier to find such
problems in your code.

The main program


Every C++ program must contain a function with the name main. This function
specifies the starting point for the computation and is called when the program starts
up. When main has finished its work and returns, execution of the program ends.
1.3 The structure of a C++ program 11

The first line of the main function in the PowersOfTwo program is an example
of a variable declaration, which reserves space for a value used by the program. In
this case, the line

int limit;

introduces a new variable named limit capable of holding a value of type int, the
standard type used to represent integers. The syntax of variable declarations is
discussed in more detail in the section on “Variables” later in this chapter. For now,
all you need to know is that this declaration creates space for an integer variable that
you can then use in the body of the main function.

The next line of the main function is

cout << "This program lists powers of two." << endl;

This line has the same effect of the single statement in HelloWorld and sends a
message to the user indicating what the program does. The identifier cout refers to
the console output stream, which is one of the facilities defined by the iostream
interface. The effect of this statement is to take the characters enclosed in quotation
marks and send them to the cout stream, followed by the end-of-line sequence
endl, which ensures that next output operation will begin on a new line.

The next two lines are concerned with asking the user to provide a value for the
variable limit. The line

cout << "Enter exponent limit: ";

also prints a message to the cout stream, just as the first line did. The purpose of
this line is to let the user know what kind of input value is required. Such messages
are generally known as prompts.

When you print a prompt requesting input from the user, it is conventional to
omit the endl value so that the prompt appears on the same line as the user input.
When the computer executes this line of the program, it will display the prompt but
leaves the console cursor—the blinking vertical bar or square that marks the current
input position—at the end of the line, waiting for the user’s value, as follows:

PowersOfTwo
This program lists powers of two.
Enter exponent limit: |
12 Overview of C++

The actual request for the input value is the line

cin >> limit;

The identifier cin represents the console input stream, which is the counterpart to
cout for reading input from the user. This statement indicates that the next value
from the cin stream should be stored in the variable limit. Moreover, because
limit is declared as an integer variable, the >> operator automatically converts the
characters typed by the user into the appropriate integer. Thus, when the user types
8 and hits the RETURN key, the effect is to set limit to 8.

The next line of the main function is a for statement, which is used to repeat a
block of code. Like all control statements in C++, the for statement is divided into
a header line, which defines the nature of the control operation, and a body, which
indicates which statements are affected by the control operation. In this case, the
division looks like this:

for (int i = 0; i <= limit; i++) { header line


cout << "2 to the " << i << " = "
loop body
<< raiseToPower(2, i) << endl;
}

The header line—which you will have a chance to understand in more detail in the
section on “The for statement” later in this chapter—indicates that the statements
in the body, whatever they are, should be repeated for each value of i beginning
with 0 and continuing up to and including the value of limit. Each execution of
the body of the loop prints a single line showing the value of 2i for the current value
of the variable i.

The single statement in the body of the loop is

cout << "2 to the " << i << " = "


<< raiseToPower(2, i) << endl;

This statement illustrates a couple of points. First, statements can be split across
more than one line; it is the semicolon that marks the end of the statement, and not
simply the end of the line. Second, this statement showcases the ability of the cout
stream to chain different output values together and to convert numeric quantities
into a printable form. The first part of the output is the character sequence

2 to the

This output is then followed by the value of the variable i, an equal sign surrounded
by spaces, the value of the function call

raiseToPower(2, i)
1.3 The structure of a C++ program 13

and finally the end of line marker. The spaces in the strings ensure that the numeric
values do not run together.

Before the program can print the output line, however, it must invoke the
raiseToPower function to see what the value should be. Calling raiseToPower
suspends the execution of the main function, which then waits until the desired
value is returned.

As is typically the case with functions, raiseToPower needs some information


from the main program in order to do its work. If you think about what raising a
number to a power involves, you quickly realize that raiseToPower needs to know
the base, which in this case is the constant 2, and the exponent, which is currently
stored in the variable i. That variable, however, is declared within the body of the
main function and is accessible only within the main program. If raiseToPower
is to have access to the value of the base and exponent, the main program must pass
them as arguments to the function by including them in parentheses after the
function name. Doing so copies those values into the corresponding parameters, as
described in the following section.

As was true in the HelloWorld program as well, the final statement in main is

return 0;

This statement indicates that the value of the main function is 0. By convention,
C++ uses the value of the main function to report the status of the entire program.
A value of 0 indicates success; any other value is taken as an indication of failure.

Function definitions
Because large programs are difficult to understand in their entirety, most programs
are broken down into several smaller functions, each of which is easier to
understand. In the PowersOfTwo program, the raiseToPower function is used to
raise an integer to a power—an operation that is not built into C++ and must
therefore be defined explicitly.

The first line of raiseToPower is the variable declaration

int result = 1;

This declaration introduces a new variable named result capable of holding


values of type int and initializes it to have the value 1.

The next statement in the function is a for loop—similar to the one you’ve
already seen in the main program—that executes its body k times. The body of the
for loop consists of the line
14 Overview of C++

result *= n;

which is C++ shorthand for the English sentence “Multiply result by n.” Because
the function initializes the value of result to 1 and then multiplies result by n a
total of k times, the variable result ends up with the value nk.

The last statement in raiseToPower is

return result;

which indicates that the function should return result as the value of the function.

1.4 Variables
Data values in a program are usually stored in variables, which are named locations
in memory capable of holding a particular data type. You have already seen
examples of variables in the PowersOfTwo program and are almost certainly
familiar with the basic concept from your earlier programming experience. The
purpose of this section is to outline the rules for using variables in C++.

Variable declarations
In C++, you must declare each variable before you use it. The primary function of
declaring a variable is to make an association between the name of the variable and
the type of value that variable contains. The placement of the declaration in a
program also determines the scope of the variable, which is the region in which that
variable is accessible.

The usual syntax for declaring a variable is

type namelist;

where type indicates the data type and namelist is a list of variable names separated
by commas. In most cases, each declaration introduces a single variable name. For
example, the function main in PowersOfTwo begins with the line

int limit;

which declares the variable limit to be of type int. You can, however, declare
several variable names at once, as in the following declaration, which declares three
variables named n1, n2, and n3:

double n1, n2, n3;

In this case, the variables are each declared to be of type double, which is the type
C++ uses to represent numbers that can have fractional parts. The name double is
1.4 Variables 15

short for double-precision floating-point, but there is no reason to worry about what
all those terms mean. This declaration appears in the AddThreeNumbers program
in Figure 1-4, which reads in three numbers and writes out their sum.

It is important to remember that both the name and the type of a variable remain
fixed throughout its lifetime but that the value of that variable will typically change
as the program runs. To emphasize the dynamic nature of the value of a variable, it
often helps to diagram variables as boxes in which the name appears outside as a
label on the box and the value appears on the inside. For example, you might
diagram the declaration of limit like this:

limit

Assigning a value to limit overwrites any previous contents of the box, but does
not change the name or the type.

In C++, the initial contents of a variable are undefined. If you want a variable to
have a particular value, you need to initialize it explicitly. To do so, all you need to
do is include an equal sign and a value after a variable name. Thus, the declaration

int result = 1;

F I G U R E 1 - 4 Program to add three numbers

/*
* File: AddThreeNumbers.cpp
* -------------------------
* This program adds three floating-point numbers and prints their sum.
*/
#include <iostream>
using namespace std;
int main() {
double n1, n2, n3;
cout << "This program adds three numbers." << endl;
cout << "1st number: ";
cin >> n1;
cout << "2nd number: ";
cin >> n2;
cout << "3rd number: ";
cin >> n3;
double sum = n1 + n2 + n3;
cout << "The sum is " << sum << endl;
return 0;
}
16 Overview of C++

is a shorthand for the following code, in which the declaration and assignment are
separate:

int result;

result = 1;

An initial value specified as part of a declaration is called an initializer.

Naming conventions
The names used for variables, functions, types, constants, and so forth are
collectively known as identifiers. In C++, the rules for identifier formation are

1. The name must start with a letter or the underscore character (_).
2. All other characters in the name must be letters, digits, or the underscore. No
spaces or other special characters are permitted in names.
3. The name must not be one of the reserved keywords listed in Table 1-1.

Uppercase and lowercase letters appearing in an identifier are considered to be


different. Thus, the name ABC is not the same as the name abc. Identifiers can be
of any length, but C++ compilers are not required to consider any more than the
first 31 characters in determining whether two names are identical.

You can improve your programming style by adopting conventions for


identifiers that help readers identify their function. In this text, names of variables
and functions begin with a lowercase letter, such as limit or raiseToPower. The
names of classes and other programmer-defined data types begin with an uppercase
letter, as in Direction or TokenScanner. Constant values are written entirely in
uppercase, as in PI or HALF_DOLLAR. Whenever an identifier consists of several
English words run together, the usual convention is to capitalize the first letter of

T A B L E 1 - 1 Reserved words in C++

asm do inline short typeid


auto double int signed typename
bool dynamic_cast long sizeof union
break else mutable static unsigned
case enum namespace static_cast using
catch explicit new struct virtual
char extern operator switch void
class false private template volatile
const float protected this wchar_t
const_cast for public throw while
continue friend register true
default goto reinterpret_cast try
delete if return typedef
1.4 Variables 17

each word to make the name easier to read. Because that strategy doesn’t work for
constants, programmers use the underscore character to mark the word boundaries.

Local and global variables


Most variables are declared with the body of a function. Such variables are called
local variables. The scope of a local variable extends to the end of the block in
which it is declared. When the function is called, space for each local variable is
allocated for the duration of that function call. When the function returns, all its
local variables disappear.

If a variable declaration appears outside any function definition, that declaration


introduces a global variable. The scope of a global variable is the remainder of the
file in which it is declared, and it exists throughout the execution of a program.
Global variables are therefore able to store values that persist across function calls.
While that property may seem useful, the disadvantages of global variables easily
outweigh their advantages. For one thing, global variables can be manipulated by
any function in a program, and it is difficult to keep those functions from interfering
with one another. Because of the problems they so often cause, global variables are
not used in this text except to declare constants, as discussed in the following
section. Although global variables may sometimes seem tempting, you will find it
easier to manage the complexity of your programs if you avoid them as well.

Constants
As you write your programs, you will find that you often use the same constant
many times in a program. If, for example, you are performing geometrical
calculations that involve circles, the constant π comes up frequently. Moreover, if
those calculations require high precision, you might actually need all the digits that
fit into a value of type double, which means you would be working with the value
3.14159265358979323846. Writing that constant over and over again is tedious at
best, and likely to introduce errors if you type it in by hand each time instead of
cutting and pasting the value. It would be better if you could give this constant a
name and then refer to it by that name everywhere in the program. You could, of
course, simply declare it as a local variable by writing

double pi = 3.14159265358979323846;

but you would then be able to use it only within the method in which it was defined.
A better strategy is to declare it as a global constant like this:

const double PI = 3.14159265358979323846;

The keyword const at the beginning of this declaration indicates that the value will
not change after the variable is initialized, thereby ensuring that the value remains
18 Overview of C++

constant. It would not be appropriate, after all, to change the value of π (despite the
fact that a bill was introduced in 1897 into the Indiana State Legislature attempting
to do just that). The rest of the declaration consists of the type, the name, and the
value, as before. The only difference is that the name is written entirely in
uppercase to be consistent with the C++ naming conventions for constants.

Using named constants offers several advantages. First, descriptive constant


names make the program easier to read. More importantly, using constants can
dramatically simplify the problem of maintaining the code for a program as it
evolves. Even if the value of PI is unlikely to change, some “constants” in a
program specify values that might change as the program evolves, even though they
will be constant for a particular version of that program.

The importance of this principle is easiest to illustrate by historical example.


Imagine for the moment that you are a programmer in the late 1960s working on the
initial design of the ARPANET, the first large-scale computer network and the
ancestor of today’s Internet. Because resource constraints were quite serious at that
time, you would need to impose a limit—as the actual designers of the ARPANET
did in 1969—on the number of host computers that could be connected. In the early
years of the ARPANET, that limit was 127 hosts. If C++ had existed in those days,
you might have declared a constant that looked like this:

const int MAXIMUM_NUMBER_OF_HOSTS = 127;

At some later point, however, the explosive growth of networking would force you
to raise this bound. That process would be relatively easy if you used named
constants in your programs. To raise the limit on the number of hosts to 1023, it
might well be sufficient to change this declaration so that it read

const int MAXIMUM_NUMBER_OF_HOSTS = 1023;

If you used MAXIMUM_NUMBER_OF_HOSTS everywhere in your program to refer to


that maximum value, making this change would automatically propagate to every
part of the program in which the name was used.

Note that the situation would be entirely different if you had used the numeric
constant 127 instead. In that case, you would need to search through the entire
program and change all instances of 127 used for this purpose to the larger value.
Some instances of 127 might well refer to other things than the limit on the number
of hosts, and it would be just as important not to change any of those values. In the
likely event that you made a mistake, you would have a very hard time tracking
down the bug.
1.5 Data types 19

1.5 Data types


Each variable in a C++ program contains a value constrained to be of a particular
type. You set the type of the variable as part of the declaration. So far, you have
seen variables of type int and double, but these types merely scratch the surface
of the types available in C++. Programs today work with many different data types,
some of which are built into the language and some of which are defined as part of a
particular application. Learning how to manipulate data of various types is an
essential part of mastering the basics of any language, including C++.

The concept of a data type


In C++ , every data value has an associated data type. From a formal perspective, a
data type is defined by two properties: a domain, which is the set of values that
belong to that type, and a set of operations, which defines the behavior of that type.
For example, the domain of the type int includes all integers

. . . −5, −4, −3, −2, −1, 0, 1, 2, 3, 4, 5 . . .

and so on, up to the limits established by the hardware of the machine. The set of
operations applicable to values of type int includes, for example, the standard
arithmetic operations like addition and multiplication. Other types have a different
domain and set of operations.

As you will learn in the later chapters in this book, much of the power of modern
programming languages like C++ comes from the fact that you can define new data
types from existing ones. To get that process started, C++ includes several
fundamental types that are defined as part of the language. These types, which act
as the building blocks for the type system as a whole, are called atomic or
primitive types. These predefined types are grouped into five categories—integer,
floating-point, Boolean, character, and enumerated types—which are discussed in
the sections that follow.

Integer types
Although the concept of an integer seems like a simple one, C++ actually includes
several different data types for representing integer values. In most cases, all you
need to know is the type int, which corresponds to the standard representation of
an integer on the computer system you are using. In certain cases, however, you
need to be more careful. Like all data, values of type int are stored internally in
storage units that have a limited capacity. Those values therefore have a maximum
size, which limits the range of integers you can use. To get around this problem,
C++ defines three integer types—short, int, and long—distinguished from each
other by the size of their domains.
20 Overview of C++

Unfortunately, the language definition for C++ does not specify an exact range
for these three types. As a result, the range for the different integer types depends
on the machine and the compiler you’re using. In the early years of computing, the
maximum value of type int was typically 32,767, which is very small by today’s
standards. If you had wanted, for example, to perform a calculation involving the
number of seconds in a year, you could not use type int on those machines,
because that value (31,536,000) is considerably larger than 32,767. Modern
machines tend to support larger integers, but the only properties you can count on
are the following:

• The internal size of an integer cannot decrease as you move from short to int
to long. A compiler designer for C++ could, for example, decide to make
short and int the same size but could not make int smaller than short.
• The maximum value of type int must be at least 32,767 (215–1).
• The maximum value of type long must be at least 2,147,483,647 (231–1).

The designers of C++ could have chosen to define the allowable range of type
int more precisely. For example, they could have declared—as the designers of
Java did—that the maximum value of type int would be 231–1 on every machine.
Had they done so, it would be easier to move a program from one system to another
and have it behave in the same way. The ability to move a program between
different machines is called portability, which is an important consideration in the
design of a programming language.

In C++, each of the integer types int, long, and short may be preceded by the
keyword unsigned. Adding unsigned creates a new data type in which no
negative values are allowed. Unsigned values also offer twice the range of positive
values when compared to their signed counterparts. On modern machines, for
example, the maximum value of type int is typically 2,147,483,647, but the
maximum value of type unsigned int is 4,294,967,295. C++ allows the type
unsigned int to be abbreviated to unsigned, and most programmers who use
this type tend to follow this practice.

An integer constant is ordinarily written as a string of decimal digits. If the


number begins with the digit 0, however, the compiler interprets the value as an
octal (base 8) integer. Thus, the constant 040 is taken to be in octal and represents
the decimal number 32. If you prefix a numeric constant with the characters 0x, the
compiler interprets that number as hexadecimal (base 16). Thus, the constant 0xFF
is equivalent to the decimal constant 255. You can explicitly indicate that an
integer constant is of type long by adding the letter L at the end of the digit string.
Thus, the constant 0L is equal to 0, but the value is explicitly of type long.
Similarly, if you use the letter U as a suffix, the constant is taken to be unsigned.
1.5 Data types 21

Floating-point types
Numbers that include a decimal fraction are called floating-point numbers, which
are used to approximate real numbers in mathematics. C++ defines three different
floating-point types: float, double, and long double. Although ANSI C++
does not specify the exact representation of these types, the way to think about the
difference is that the longer types—where long double is longer than double,
which is in turn longer than float—allow numbers to be represented with greater
precision at the cost of occupying more memory space. Unless you are doing
exacting scientific calculation, however, the differences between these types will
not make a great deal of difference. In keeping with a common convention among
C++ programmers, this text uses the type double as its standard floating-point
type.

Floating-point constants in C++ are written with a decimal point. Thus, if 2.0
appears in a program, the number is represented internally as a floating-point value;
if the programmer had written 2, this value would be an integer. Floating-point
values can also be written in a special programmer’s style of scientific notation, in
which the value is represented as a floating-point number multiplied by an integral
power of 10. To write a number using this style, you write a floating-point number
in standard notation, followed immediately by the letter E and an integer exponent,
optionally preceded by a + or - sign. For example, the speed of light in meters per
second can be written in C++ as

2.9979E+8

where the E stands for the words times 10 to the power.

Boolean type
In the programs you write, it is often necessary to test a particular condition that
affects the subsequent behavior of your code. Typically, that condition is specified
using an expression whose value is either true or false. This data type—for which
the only legal values are the constants true and false—is called Boolean data,
after the mathematician George Boole, who developed an algebraic approach for
working with such values.

In C++, the Boolean type is called bool. You can declare variables of type
bool and manipulate them in the same way as other data objects. The operations
that apply to the type bool are described in detail in the section entitled “Boolean
operators” on page 34.
22 Overview of C++

Characters
In the early days, computers were designed to work only with numeric data and
were sometimes called number crunchers as a result. Modern computers, however,
work less with numeric data than they do with text data, that is, any information
composed of individual characters that appear on the keyboard and the screen. The
ability of modern computers to process text data has led to the development of word
processing systems, online reference libraries, electronic mail, social networks, and
a seemingly infinite supply of exciting applications.

The most primitive elements of text data are individual characters, which are
represented in C++ using the predefined data type char. The domain of type char
is the set of symbols that can be displayed on the screen or typed on the keyboard:
the letters, digits, punctuation marks, spacebar, RETURN key, and so forth.
Internally, these values are represented inside the computer by assigning each
character a numeric code. In most implementations of C++, the coding system used
to represent characters is called ASCII, which stands for the American Standard
Code for Information Interchange. The decimal values of the characters in the
ASCII set are shown in Table 1-2, where the ASCII code for any character is the
sum of the numbers at the beginning of its row and column.

Although it is important to know that characters are represented internally using


a numeric code, it is not generally useful to know what numeric value corresponds

T A B L E 1 - 2 ASCII character codes

0 1 2 3 4 5 6 7 8 9
0x \000 \001 \002 \003 \004 \005 \006 \a \b \t
1x \n \v \f \r \016 \017 \020 \021 \022 \023
2x \024 \025 \026 \027 \030 \031 \032 \033 \034 \035
3x \036 \037 space ! " # $ % & '
4x ( ) * + , - . / 0 1
5x 2 3 4 5 6 7 8 9 : ;
6x < = > ? @ A B C D E
7x F G H I J K L M N O
8x P Q R S T U V W X Y
9x Z [ \ ] ^ _ ‘ a b c
10 x d e f g h i j k l m
11 x n o p q r s t u v w
12 x x y z { | } ~ \177
1.5 Data types 23

to a particular character. When you type the letter A, the hardware logic built into
the keyboard automatically translates that character into the ASCII code 65, which
is then sent to the computer. Similarly, when the computer sends the ASCII code
65 to the screen, the letter A appears.

You can write a character constant in C++ by enclosing the character in single
quotes. Thus, the constant 'A' represents the internal code of the uppercase letter
A. In addition to the standard characters, C++ allows you to write special characters
in a multicharacter form beginning with a backward slash (\). This form is called
an escape sequence. Table 1-3 shows the escape sequences that C++ supports.

Strings
Characters are most useful when they are collected together into sequential units. In
programming, a sequence of characters is called a string. So far, the strings you’ve
seen in the HelloWorld and PowersOfTwo programs have been used simply to
display messages on the screen, but they have many more applications than that.

You write string constants in C++ by enclosing the characters contained within
the string in double quotes. As with character, C++ uses the escape sequences from
Table 1-3 to represent special characters. If two or more string constants appear
consecutively in a program, the compiler concatenates them together. The most
important implication of this rule is that you can break a long string over several
lines so that it doesn’t end up running past the right margin of your program.

T A B L E 1 - 3 Escape sequences

\a Audible alert (beeps or rings a bell)


\b Backspace
\f Formfeed (starts a new page)
\n Newline (moves to the beginning of the next line)
\r Return (returns to the beginning of the current line without advancing)
\t Tab (moves horizontally to the next tab stop)
\v Vertical tab (moves vertically to the next tab stop)
\0 Null character (the character whose ASCII code is 0)
\\ The character \ itself
\' The character ' (requires the backslash only in character constants)
\" The character " (requires the backslash only in string constants)
\ddd The character whose ASCII code is the octal number ddd
24 Overview of C++

Given that they are essential to so many applications, all modern programming
languages include special features for working with strings. Unfortunately, C++
complicates the issue by defining two different string types: an older style inherited
from C and a more sophisticated string library that supports the object-oriented
paradigm. To minimize confusion, this text uses the string library wherever
possible, and you should—for the most part—feel free to ignore the fact that two
string models exist. The times when that complexity raises its ugly head are
outlined in Chapter 3, which covers the string library in more detail. For the
moment, you can simply imagine that C++ offers a built-in data type called string
whose domain is the set of all sequences of characters. You can declare variables of
type string and pass string values back and forth between functions as arguments
and results.

The fact that string is a library type and not a built-in feature does have a few
implications. If you use the type name string in a program, you need to add the
string library to the list of #include lines, like this:

#include <string>

Moreover, because the string type is part of the standard library namespace, the
compiler will recognize the type name only if you have included the line

using namespace std;

at the beginning of the file, as the programs in this book invariably do.

Enumerated types
As the discussion of ASCII codes in the preceding section makes clear, computers
store character data in integer by assigning a number to each character. This idea of
encoding data as integers by numbering the elements of the domain is actually a
much more general principle. C++ allows you to define new types simply by listing
the elements in their domain. Such types are called enumerated types.

The syntax for defining an enumerated type is

enum typename { namelist };

where typename is the name of the new type and namelist is a list of the constants in
the domain, separated by commas. In this book, all type names start with an
uppercase letter, and the names of the enumeration constants are written entirely in
uppercase. For example, the following definition introduces a new Direction
type whose values are the four compass directions:

enum Direction { NORTH, EAST, SOUTH, WEST };


1.5 Data types 25

When the C++ compiler encounters this definition, it assigns values to the constant
names by numbering them consecutively starting with 0. Thus, NORTH is assigned
the value 0, EAST is assigned the value 1, SOUTH is assigned the value 2, and WEST
is assigned the value 3.

C++ allows you to assign explicit underlying values to each of the constants of
an enumerated type. For example, the type declaration

enum Coin {
PENNY = 1,
NICKEL = 5,
DIME = 10,
QUARTER = 25,
HALF_DOLLAR = 50,
DOLLAR = 100
};

introduces an enumerated type for U.S. coinage in which each constant is defined to
equal the monetary value of that coin. If you supply values for some of the
constants but not others, the C++ compiler will automatically choose values for the
unassigned constants by numbering them consecutively after the last value you
supplied. Thus, the type declaration

enum Month {
JANUARY = 1,
FEBRUARY,
MARCH,
APRIL,
MAY,
JUNE,
JULY,
AUGUST,
SEPTEMBER,
OCTOBER,
NOVEMBER,
DECEMBER
};

introduces a type for the months of the year in which JANUARY has the value 1,
FEBRUARY has the value 2, and so forth up to DECEMBER, which has the value 12.

Compound types
The atomic types described in the preceding sections form the basis of a very rich
type system that allows you to create new types from existing ones. Moreover,
because C++ represents a synthesis of the object-oriented and procedural
26 Overview of C++

paradigms, the type system includes both objects and more traditional structures.
Learning how to define and manipulate these types is, to a large extent, the theme of
this entire book. It therefore does not make sense to squeeze a complete description
of these types into Chapter 1. That’s what the rest of the chapters are for.

Over the years of teaching this material at Stanford, we have discovered that you
are much more likely to master the concepts of object-oriented programming if the
details of defining classes and objects are presented after you have had a chance to
use them in a high-level way. This book adopts that strategy and postpones any
discussion of how to create your own objects until Chapter 6, at which point you
will have had plenty of time to discover just how useful objects can be.

1.6 Expressions
Whenever you want a program to perform calculations, you need to write an
expression that specifies the necessary operations in a form similar to that used for
expressions in mathematics. For example, suppose that you wanted to solve the
quadratic equation

ax2 + bx + c = 0

As you know from high-school mathematics, this equation has two solutions given
by the formula

- b + b 2 - 4ac
x =
2a

The first solution is obtained by using + in place of the ± symbol; the second is
obtained by using – instead. In C++, you could compute the first of these solutions
by writing the following expression:

(-b + sqrt(b * b - 4 * a * c)) / (2 * a)

There are a few differences in form: multiplication is represented explicitly by a *,


division is represented by a /, and the square root function (which comes from a
library called <cmath> described in detail in Chapter 2) is written using the name
sqrt rather than a mathematical symbol. Even so, the C++ form of the expression
captures the intent of its mathematical counterpart in a way that is quite readable,
particularly if you’ve written programs in any modern programming language.

In C++, an expression is composed of terms and operators. A term, such as the


variables a, b, and c or the constants 2 and 4 in the preceding expression, represents
a single data value and must be either a constant, a variable, or a function call. An
operator is a character (or sometimes a short sequence of characters) that indicates a
1.6 Expressions 27

computational operation. A list of the operators available in C++ appears in


Table 1-4. The table includes familiar arithmetic operators like + and - along with
several others that pertain only to types introduced in later chapters.

Precedence and associativity


The point of listing all the operators in a single table is to establish how they relate
to one another in terms of precedence, which is a measure of how tightly an
operator binds to its operands in the absence of parentheses. If two operators
compete for the same operand, the one that appears higher in the precedence table is
applied first. Thus, in the expression

(-b + sqrt(b * b - 4 * a * c)) / (2 * a)

the multiplications b * b and 4 * a * c are performed before the subtraction


because * has a higher precedence than -. It is, however, important to note that
the - operator occurs in two forms. Operators that connect two operands are called
binary operators; operators that take just one operand are called unary operators.
When a minus sign is written in front of a single operand, as in -b, it is interpreted
as a unary operator signifying negation. When it appears between two operands, as
it does inside the argument to sqrt, the minus sign is a binary operator signifying

T A B L E 1 - 4 Operators available in C++

Operators organized into precedence groups Associativity


() [] -> . left
unary operators: - ++ -- ! & * ~ (type) sizeof right
* / % left
+ - left
<< >> left
< <= > >= left
== != left
& left
^ left
| left
&& left
|| left
?: right
= op= right
28 Overview of C++

subtraction. The precedence of the unary and binary versions of an operator are
different and are listed separately in the precedence table.

If two operators have the same precedence, they are applied in the order
specified by their associativity, which indicates whether that operator groups to the
left or to the right. Most operators in C++ are left-associative, which means that the
leftmost operator is evaluated first. A few operators—most notably the assignment
operator discussed in its own section later in this chapter—are right-associative,
which mean that they group from right to left. The associativity for each operator
appears in Table 1-4.

The quadratic formula illustrates the importance of paying attention to


precedence and associativity rules. Consider what would happen if you wrote the
expression without the parentheses around 2 * a, as follows:

(-b + sqrt(b * b - 4 * a * c)) / 2 * a

Without the parentheses, the division operator would be performed first because /
and * have the same precedence and associate to the left. This example illustrates
the use of the bug icon to mark code that is intentionally incorrect to make sure that
you don’t copy it into your own programs.

Mixing types in an expression


In C++, you can write an expression that includes values of different numeric types.
If C++ encounters an operator whose operands are of different types, the compiler
automatically converts the operands to a common type by choosing the type that
appears closest to the top of the hierarchy in Table 1-5. The result of applying the
operation is always that of the arguments after any conversions are applied. This
convention ensures that the result of the computation is as precise as possible.

T A B L E 1 - 5 Type conversion hierarchy for numeric types

long double most precise


double
float
unsigned long
long
unsigned int
int
unsigned short
short
char least precise
1.6 Expressions 29

As an example, suppose that n is declared as an int, and x is declared as a


double. The expression

n + 1

is evaluated using integer arithmetic and produces a result of type int. The
expression

x + 1

however, is evaluated by converting the integer 1 to the floating-point value 1.0 and
adding the results together using double-precision floating-point arithmetic, which
results in a value of type double.

Integer division and the remainder operator


The fact that applying an operator to two integer operands generates an integer
result leads to an interesting situation with respect to the division operator. If you
write an expression like

9 / 4

C++’s rules specify that the result of this operation must be an integer, because both
operands are of type int. When C++ evaluates this expression, it divides 9 by 4
and discards any remainder. Thus, the value of this expression in C++ is 2, not
2.25.

If you want to compute the mathematically correct result of 9 divided by 4, at


least one of the operands must be a floating-point number. For example, the three
expressions

9.0 / 4
9 / 4.0
9.0 / 4.0

each produce the floating-point value 2.25. The decimal fraction is thrown away
only if both operands are of type int. The operation of discarding a decimal
fraction is called truncation.

The / operator in C++ is closely associated with the % operator, which returns
the remainder left over when the first operand is divided by the second. For
example, the value of

9 % 4
30 Overview of C++

is 1, since 4 goes into 9 twice, with 1 left over. The following are some other
examples of the % operator:
0 % 4 = 0 19 % 4 = 3
1 % 4 = 1 20 % 4 = 0
4 % 4 = 0 2001 % 4 = 1

The / and % operators turn out to be extremely useful in a wide variety of


programming applications. You can, for example, use the % operator to test whether
one number is divisible by another; to determine whether an integer n is divisible by
3, you just check whether the result of the expression n % 3 is 0.

It is, however, important to use caution if either or both of the operands to / and
% might be negative, because the results may differ from machine to machine. On
most machines, division truncates its result toward 0, but this behavior is not
actually guaranteed by the ANSI standard. In general, it is good programming
practice to avoid—as this book does—using these operators with negative values.

Type casts
In C++, you can specify explicit conversion by using what is called a type cast,
which specifies an explicit conversion from one type to another. In C++, type casts
are usually written by specifying the name of the desired type followed by the value
you wish to convert in parentheses. For example, if num and den are declared as
integers, you can compute the floating-point quotient by writing

quotient = double(num) / den;

The first step in evaluating the expression is to convert num to a double, after
which the division is performed using floating-point arithmetic as described in the
section on “Mixing types in an expression” earlier in this chapter.

As long as the conversion moves upward in the hierarchy shown in Table 1-5,
the conversion involves no loss of information. If, however, you convert a value of
a more precise type to a less precise one, some information may be lost. For
example, if you use a type cast to convert a value of type double to type int, any
decimal fraction is simply dropped. Thus, the value of the expression

int(1.9999)

is the integer 1.

The assignment operator


In C++, assignment of values to variables is built into the expression structure.
The = operator takes two operands, just like + or *. The left operand must indicate
a value that can change, which is typically a variable name. When the assignment
1.6 Expressions 31

operator is executed, the expression on the right-hand side is evaluated, and the
resulting value is then stored in the variable that appears on the left-hand side.
Thus, if you evaluate an expression like

result = 1

the effect is that the value 1 is assigned to the variable result. In most cases,
assignment expressions of this sort appear in the context of simple statements,
which are formed by adding a semicolon after the expression, as in the line

result = 1;

Such statements are often called assignment statements.

The assignment operator converts the type of the value on the right-hand side so
that it matches the declared type of the variable. Thus, if the variable total is
declared to be of type double, and you write the assignment statement

total = 0;

the integer 0 is converted into a double as part of making the assignment. If n is


declared to be of type int, the assignment

n = 3.14159265;

has the effect of setting n to 3, because the value is truncated to fit in the integer
variable.

Even though assignment operators usually occur in the context of simple


statements, they can also be incorporated into larger expressions, in which case the
result of applying the assignment operator is simply the value assigned. For
example, the expression

z = (x = 6) + (y = 7)

has the effect of setting x to 6, y to 7, and z to 13. The parentheses are required in
this example because the = operator has a lower precedence than +. Assignments
that are written as part of larger expressions are called embedded assignments.

Although there are contexts in which embedded assignments are convenient,


they often make programs more difficult to read because the assignment is easily
overlooked in the middle of a complex expression. For this reason, this text limits
the use of embedded assignments to a few special circumstances in which they seem
to make the most sense. Of these, the most important is when you want to set
several variables to the same value. C++’s definition of assignment as an operator
32 Overview of C++

makes it possible, instead of writing separate assignment statements, to write a


single statement like

n1 = n2 = n3 = 0;

which has the effect of setting all three variables to 0. This statement works
because C++ evaluates assignment operators from right to left. The entire statement
is therefore equivalent to

n1 = (n2 = (n3 = 0));

The expression n3 = 0 is evaluated, which sets n3 to 0 and then passes 0 along as


the value of the assignment expression. That value is assigned to n2, and the result
is then assigned to n1. Statements of this sort are called multiple assignments.

As a programming convenience, C++ allows you to combine assignment with a


binary operator to produce a form called a shorthand assignment. For any binary
operator op, the statement

variable op= expression;

is equivalent to

variable = variable op (expression);

where the parentheses are included to emphasize that the entire expression is
evaluated before op is applied. Thus, the statement

balance += deposit;

is a shorthand for

balance = balance + deposit;

which adds deposit to balance.

Because this same shorthand applies to any binary operator in C++, you can
subtract the value of surcharge from balance by writing

balance -= surcharge;

Similarly, you can divide the value of x by 10 using

x /= 10;
1.6 Expressions 33

Increment and decrement operators


Beyond the shorthand assignment operators, C++ offers a further level of
abbreviation for the particularly common programming operations of adding or
subtracting 1 from a variable. Adding 1 to a variable is called incrementing it;
subtracting 1 is called decrementing it. To indicate these operations in an
extremely compact form, C++ uses the operators ++ and --. For example, the
statement

x++;

in C++ has the same effect on the variable x as

x += 1;

which is itself short for

x = x + 1;

Similarly,

y--;

has the same effect as

y -= 1;

or

y = y - 1;

As it happens, these operators are more intricate than the previous examples
would suggest. To begin with, each of these operators can be written in two ways.
The operator can come after the operand to which it applies, as in

x++

or before the operand, as in

++x

The first form, in which the operator follows the operand, is called the postfix form,
the second, the prefix form.

If all you do is execute the ++ operator in isolation—as you do in the context of


a separate statement or the standard for loop patterns—the prefix and postfix
operators have precisely the same effect. You notice the difference only if you use
34 Overview of C++

these operators as part of a larger expression. Then, like all operators, the ++
operator returns a value, but the value depends on where the operator is written
relative to the operand. The two cases are as follows:

x++ Calculates the value of x first, and then increments it. The value
returned to the surrounding expression is the original value before the
increment operation is performed.

++x Increments the value of x first, and then uses the new value as the
value of the ++ operation as a whole.

The -- operator behaves similarly, except that the value is decremented rather than
incremented.

You may wonder why would anyone use such an arcane feature. The ++ and --
operators are certainly not essential. Moreover, there are not many circumstances in
which programs that embed these operators in larger expressions are demonstrably
better than those that use a simpler approach. On the other hand, ++ and -- are
firmly entrenched in the historical tradition shared by the languages C, C++, and
Java. Programmers use them so frequently that they have become essential idioms
in these languages. In light of their widespread use in programs, you need to
understand these operators so that you can make sense of existing code.

Boolean operators
C++ defines three classes of operators that manipulate Boolean data: the relational
operators, the logical operators, and the ?: operator. The relational operators are
used to compare two values. C++ defines six relational operators, as follows:

== Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

When you write programs that test for equality, be careful to use the == operator,
which is composed of two equal signs. A single equal sign is the assignment
operator. Since the double equal sign violates conventional mathematical usage,
replacing it with a single equal sign is a particularly common mistake. This mistake
can also be very difficult to track down because the C++ compiler does not usually
catch it as an error. A single equal sign turns the expression into an embedded
assignment, which is perfectly legal in C++; it just isn’t at all what you want.
1.6 Expressions 35

The relational operators can be used to compare atomic data values like integers,
floating-point numbers, Boolean values, and characters, but those operators can also
be applied to many of the types supplied by libraries, such as string.

In addition to the relational operators, C++ defines three logical operators that
take Boolean operands and combine them to form other Boolean values:

! Logical not (true if the following operand is false)


&& Logical and (true if both operands are true)
|| Logical or (true if either or both operands are true)

These operators are listed in decreasing order of precedence.

Although the operators &&, ||, and ! closely resemble the English words and,
or, and not, it is important to remember that English can be somewhat imprecise
when it comes to logic. To avoid that imprecision, it is often helpful to think of
these operators in a more formal, mathematical way. Logicians define these
operators using truth tables, which show how the value of a Boolean expression
changes as the values of its operands change. The truth table in Table 1-6 illustrates
the result for each of the logical operators, given all possible values of the variables
p and q.

Whenever a C++ program evaluates an expression of the form

exp1 && exp2

or
exp1 || exp2

the individual subexpressions are always evaluated from left to right, and evaluation
ends as soon as the result can be determined. For example, if exp1 is false in the
expression involving &&, there is no need to evaluate exp2 since the final result will
always be false. Similarly, in the example using ||, there is no need to evaluate
the second operand if the first operand is true. This style of evaluation, which
stops as soon as the result is known, is called short-circuit evaluation.

T A B L E 1 - 6 Truth table for the logical operators

p q p && q p || q !p
false false false false true
false true false true true
true false false true false
true true true true false
36 Overview of C++

The C++ programming language includes another Boolean operator called ?:


that can be extremely useful in certain situations. In programming parlance, the
name of this operator is always pronounced as question-mark colon, even though
the two characters do not appear adjacent to each other in the code. Unlike the
other operators in C++, ?: is written in two parts and requires three operands. The
general form of the operation is

(condition) ? exp1 : exp2

The parentheses are not technically required, but C++ programmers often include
them to emphasize the boundaries of the conditional test.

When a C++ program encounters the ?: operator, it first evaluates the condition.
If the condition turns out to be true, exp1 is evaluated and used as the value of the
entire expression; if the condition is false, the value is the result of evaluating
exp2. For example, you can use the ?: operator to assign to max either the value of
x or the value of y, whichever is greater, as follows:

max = (x > y) ? x : y;

1.7 Statements
Programs in C++ are composed of functions, which are made up in turn of
statements. As in most languages, statements in C++ fall into one of two principal
classifications: simple statements that perform some action and control statements
that affect the way in which other statements are executed. The sections that follow
review the principal statement forms available in C++, giving you the tools you
need to write your own programs.

Simple statements
The most common statement in C++ is the simple statement, which consists of an
expression followed by a semicolon:

expression;

In most cases, the expression is a function call, an assignment, or a variable


followed by the increment or decrement operator.

Blocks
As C++ is defined, control statements typically apply to a single statement. When
you are writing a program, you often want a particular control statement to apply to
a whole group of statements. To indicate that a sequence of statements is part of a
coherent unit, you can assemble those statements into a block, which is a collection
of statements enclosed in curly braces, as follows:
1.7 Statements 37

{
statement1
statement2
. . .
statementn
}

When the C++ compiler encounters a block, it treats the entire block as a single
statement. Thus, whenever the notation statement appears in a pattern for one of the
control forms, you can substitute for it either a single statement or a block. To
emphasize that they are statements as far as the compiler is concerned, blocks are
sometimes referred to as compound statements. In C++, the statements in any
block may be preceded by declarations of variables.

The statements in the interior of a block are usually indented relative to the
enclosing context. The compiler ignores the indentation, but the visual effect is
extremely helpful to the human reader, because it makes the structure of the
program jump out at you from the format of the page. Empirical research has
shown that indenting three or four spaces at each new level makes the program
structure easiest to see; the programs in this text use three spaces for each new level.
Indentation is critical to good programming, so you should strive to develop a
consistent indentation style in your programs.

The if statement
In writing a program, you will often want to check whether some condition applies
and use the result of that check to control the subsequent execution of the program.
This type of program control is called conditional execution. The easiest way to
express conditional execution in C++ is by using the if statement, which comes in
two forms:

if (condition) statement
if (condition) statement else statement

You use the first form of the if statement when your solution strategy calls for a set
of statements to be executed only if a particular Boolean condition is true. If the
condition is false, the statements that form the body of the if statement are
simply skipped. You use the second form of the if statement for situations in
which the program must choose between two independent sets of actions based on
the result of a test. This statement form is illustrated by the following code, which
reports whether an integer n is even or odd.
38 Overview of C++

if (n % 2 == 0) {
cout << "That number is even." << endl;
} else {
cout << "That number is odd." << endl;
}

As with any control statement, the statements controlled by the if statement can
be either a single statement or a block. Even if the body of a control form is a single
statement, you are free to enclose it in a block if you decide that doing so improves
the readability of your code. The programs in this book enclose the body of every
control statement in a block unless the entire statement—both the control form and
its body—is so short that it fits on a single line.

The switch statement


The if statement is ideal for those applications in which the program logic calls for
a two-way decision point: some condition is either true or false, and the program
acts accordingly. Some applications, however, call for more complicated decision
structures involving several mutually exclusive cases: in one case, the program
should do x; in another case, it should do y; in a third, it should do z; and so forth.
In many applications, the most appropriate statement to use for such situations is the
switch statement, which has the following syntactic form:

switch (e) {
case c1:
statements
break;
case c2:
statements
break;
. . . more case clauses . . .
default:
statements
break;
}

The expression e is called the control expression. When the program executes a
switch statement, it evaluates the control expression and compares it against the
values c1, c2, and so forth, each of which must be a constant. If one of the constants
matches the value of the control expression, the statements in the associated case
clause are executed. When the program reaches the break statement at the end of
the clause, the operations specified by that clause are complete, and the program
continues with the statement that follows the entire switch statement.
1.7 Statements 39

The default clause is used to specify what action occurs if none of the
constants match the value of the control expression. The default clause, however,
is optional. If none of the cases match and there is no default clause, the program
simply continues on with the next statement after the switch statement without
taking any action at all. To avoid the possibility that the program might ignore an
unexpected case, it is good programming practice to include a default clause in
every switch statement unless you are certain you have enumerated all the
possibilities.

The code pattern I’ve used to illustrate the syntax of the switch statement
deliberately suggests that break statements are required at the end of each clause.
In fact, C++ is defined so that if the break statement is missing, the program starts
executing statements from the next clause after it finishes the selected one. While
this design can be useful in some cases, it causes many more problems than it
solves. To reinforce the importance of remembering to exit at the end of each case
clause, the programs in this text include a break or return statement in each such
clause.

The one exception to this rule is that multiple case lines specifying different
constants can appear together, one after another, before the same statement group.
For example, a switch statement might include the following code:

case 1:
case 2:
statements
break;

which indicates that the specified statements should be executed if the select
expression is either 1 or 2. The C++ compiler treats this construction as two case
clauses, the first of which is empty. Because the empty clause contains no break
statement, a program that selects the first path simply continues on with the second
clause. From a conceptual point of view, however, you are better off if you think of
this construction as a single case clause representing two possibilities.

The constants in a switch statement must be a scalar type, which is defined in


C++ as a type that uses an integer as its underlying representation. In particular,
characters are often used as case constants, as illustrated by the following function,
which tests to see if its argument is a vowel:
40 Overview of C++

bool isVowel(char ch) {


switch (ch) {
case 'A': case 'E': case 'I': case 'O': case 'U':
case 'a': case 'e': case 'i': case 'o': case 'u':
return true;
default:
return false;
}
}

Enumerated types also qualify as scalar types, as illustrated by the function

string directionToString(Direction dir) {


switch (dir) {
case NORTH: return "NORTH";
case EAST: return "EAST";
case SOUTH: return "SOUTH";
case WEST: return "WEST";
default: return "???";
}
}

which converts a Direction value to a string. The default clause returns "???"
if the internal value of dir does not match any of the Direction constants.

As a second example of using switch with enumerated types, the following


function returns the number of days for a given month and year:

int daysInMonth(Month month, int year) {


switch (month) {
case APRIL:
case JUNE:
case SEPTEMBER:
case NOVEMBER:
return 30;
case FEBRUARY:
return (isLeapYear(year)) ? 29 : 28;
default:
return 31;
}
}

This code assumes the existence of a function isLeapYear(year) that tests


whether year is a leap year. You can implement isLeapYear using the logical
operators && and ||, as follows:
Exploring the Variety of Random
Documents with Different Content
NOTES
[1] L'un des interrogés dit que le roi en avait cinq. D'après une autre
relation, le nombre en serait monté à la fin jusqu'à dix-sept.

[2] Ceci se rapporte à l'interprétation du mot: né, geboren.

[3] C'est aussi ce que dit Montaigne dans ses Essais.

[4] Sans doute Copernic qui termina vers 1530 son livre De orbium
cœlestium revolutionibus, imprimé, en 1543, à Nuremberg, avec une
dédicace au pape Paul III. Dès 1540, une lettre de son disciple Rheticus fit
connaître le nouveau système.

[5] Voyez la belle ballade anglaise sur le martyre de Barleycorn.

[6] Il semble qu'on retrouve ces tristes pensées dans le beau portrait de
Luther mort, qui se trouve dans la collection du libraire Zimmer à Heidelberg;
ce portrait exprime aussi la continuation d'un long effort.

[7] Nom d'un village près duquel Luther possédait une petite terre.

[8] Luther appelle Louis ce landgrave, qui s'appelait effectivement Albert-


le-Dénaturé, et vivait en 1288. Sa femme, Marguerite était fille de l'empereur
Frédéric II; son fils est Frédéric I, dit le Mordu.

[9] Voyez le Voyage de Montaigne.

[10] Il est inutile de relever les erreurs grossières dont fourmille ce


chapitre.

[11] Mélanchton fait remarquer que saint Augustin n'exprime pas cette
opinion dans ses écrits de controverse.
RENVOIS
DU TOME TROISIÈME.

Renvoi Page Ligne


[r1] 3, 19. Otto Pack.—Cochlæus, 171.
[r2] 4, 11. Cette ligue.—Ukert, 216.
[r3] 5, 15. Tu crains que.—Luther Werke, t. IX, 231.
[r4] 6, 24. Mémoire de Luther.—Ibid. t. IX, 297.
[r5] 20, 23. L'Espagnol disait.—Ibid. t. IX, 414.
[r6] 23, 14. Luther écrit.—Ibid. t. IX, 459.
[r7] 29, 15. Comment l'Évangile.—Ibid. t. II, 391, 199.
[r8] 35, 17. Nouvelle sur les Anabaptistes.—Ibid. t. II, 328.
[r9] 40, 20. Les anabaptistes soumis.—Ibid. t. II, 365.
[r10] 42, 4. Entretien.—Ibid. t. II, 376.
[r11] 49, 11. Le 19 janvier.—Ibid. t. II, 400.
[r12] 51, 3. Préface de Luther.—Ibid. t. II, 332.
[r13] 60, 14. Les instructions.—Bossuet en a donné le texte
dans son histoire des Variations de l'Église
protestante.—t. I, 328, 199.
[r14] 72, 3. Celui qui insulte.—Tischr. 241.
[r15] 72, 8. Le droit saxon.—Ibid. 315 bis.
[r16] 72, 14. Il n'y a point de doute.—Ibid. 116.
[r17] 72, 22. On disait à Luther.—Ibid. 312 bis.
[r18] 73, 11. Lettre à un ami.—Ibid. 313 bis.
[r19] 73, 20. Il n'est guère plus possible.—Ibid. 315 bis.
[r20] 74, 4. La plus grande grâce.—Ibid. 313.
[r21] 74, 20. Au jour de la.—Ibid. 316 bis.
[r22] 75, 6. Le docteur M.—Ibid. 320.
[r23] 75, 18. En 1541.—Ibid. 264 bis.
[r24] 76, 4. La première année.—Ibid. 313 bis.
[r25] 76, 19. Lucas Cranach.—Ibid. 314.
[r26] 77, 19. On trouve l'image.—Ibid. 312 bis.
[r27] 78, 6. Les petits enfans.—Ibid. 42 bis.
[r28] 78, 3. On amena.—Ibid. 124.
[r29] 78, 20. Servez.—Ibid. 10 bis.
[r30] 79, 3. Au premier jour.—Ibid. 314 bis.
[r31] 79, 13. Après qu'il eut.—Ibid. 47.
[r32] 79, 21. Il disait à son.—Ibid. 49 bis.
[r33] 79, 25. Les enfans sont les plus heureux.—Ibid. 134.
[r34] 80, 10. Une autre fois.—Ibid. 134 bis.
[r35] 80, 19. Comme maître.—Ibid. 45 bis.
[r36] 81, 1. Quels ont dû être.—Ibid. 47.
[r37] 81, 17. Il est touchant.—Ibid. 42-43 passim.
[r38] 81, 24. Le 9 avril 1539.—Ibid. 363.
[r39] 82, 16. Le 18 avril.—Ibid. 423.
[r40] 83, 13. Supportons.—Lettre V, 726.
[r41] 83, 22. Un soir.—Tischr. 43 bis.
[r42] 84, 1. Vers le soir.—Ibid. 24 bis.
[r43] 85, 10. Le petit enfant.—Tischred. 32, verso.
[r44] 86, 23. Dans les choses divines.—Ibid. 69.
[r45] 87, 14. Le décalogue.—Ibid. 112, verso.
[r46] 87, 18. On demandait au docteur.—Ibid. 362.
[r47] 88, 1. Cicéron.—Ibid. 425.
[r48] 88, 12. On demandait à Luther.—Ibid. 106.
[r49] 88, 25. Le docteur soupirait.—Ibid. 11, verso.
[r50] 89, 11. Autrefois.—Ibid. 311.
[r51] 89, 21. Que sont les saints.—Cochlæus, Vie de Luther,
226.
[r52] 90, 10. Nos adversaires.—Tischred. 447.
[r53] 90, 18. Pourquoi enseigne-t-on?—Luth. Werke, t. II,
16.
[r54] 92, 8. Le Pater noster.—Tischreden, 153.
[r55] 93, 3. L'évangile de saint Jean.—Ukert, 18.
[r56] 95, 28. Ambroise.—Tischreden, 383.
[r57] 96, 7. Saint Augustin.—Ibid. 98.
[r58] 97, 11. Les nominaux.—Ibid. 384.
[r59] 98, 15. Le D. Staupitz.—Ibid. 385.
[r60] 99, 11. Jean Huss.—Ibid. 386.
[r61] 99, 26. Jean Huss était.—Ibid. 127.
[r62] 100, 4. La tête de l'antichrist.—Ibid. 241.
[r63] 100, 6. C'est ma pauvre condition.—Ibid. 249.
[r64] 100, 18. Les papistes.—Ibid. 255.
[r65] 100, 28. Le pape le dit.—Ibid. 259.
[r66] 101, 6. D'autres ont attaqué les mœurs.—Ibid. 192.
[r67] 101, 10. Des conciles.—Ibid. 371-76.
[r68] 102, 14. Des biens ecclésiastiques.—Ibid. 380.
[r69] 103, 17. Le proverbe a raison.—Ibid. 60.
[r70] 104, 7. En Italie.—Ibid. 275.
[r71] 104, 26. Dans les disputes.—Ibid. 271.
[r72] 105, 3. La moinerie.—Ibid. 272.
[r73] 123, 4. Oh! combien je tremblais.—Ibid. 181.
[r74] 124, 9. Je n'aime pas que Philippe.—Ibid. 197.
[r75] 124, 14. Le docteur Jonas lui disait.—Ibid. 113.
[r76] 124, 24. Je veux que l'on enseigne.—Ibid. 116.
[r77] 125, 4. Le docteur Erasmus Alberus.—Ibid. 184.
[r78] 125, 16. Albert Dürer.—Ibid. 425.
[r79] 125, 20. Oh! que j'eusse été heureux.—Luth. Werke, t.
IX, 245.
[r80] 125, 27. Rien n'est plus agréable.—Tischreden, 182.
[r81] 126, 3. Parmi les qualités.—Ibid. 183.
[r82] 126, 7. Dans le traité.—Seckendorf, livre I, 202.
[r83] 128, 4. Le docteur Luther disait.—Tischreden, 105.
[r84] 128, 8. Si je meurs.—Ibid. 356.
[r85] 128, 13. Dans la colère.—Ibid. 145.
[r86] 131, 4. Il n'est pas d'alliance.—Ibid. 331.
[r87] 132, 19. La nouvelle étant venue.—Ibid. 274.
[r88] 134, 12. La nuit qui précéda la mort.—Ibid. 360.
[r89] 138, 3. Il vaut mieux.—Ibid. 347.
[r90] 139, 13. Le droit est une belle fiancée.—Ibid. 273.
[r91] 139, 28. Avant moi, il n'y a eu.—Ibid. 402.
[r92] 142, 22. Voilà comme agissent.—Ibid. 403.
[r93] 143, 12. Bon peuple, veuillez agréer.—Ibid. 407.
[r94] 145, 11. Je suis maintenant.—Ibid. 102.
[r95] 146, 8. La loi sans doute.—Ibid. 128.
[r96] 146, 17. Pour me délivrer entièrement.—Tischreden,
133.
[r97] 147, 1. Il n'est qu'un seul point.—Ibid. 140.
[r98] 147, Luther en parlant.—Ibid. 147.
[r99] 147, 8. Le diable veut seulement.—Ibid. 142.
[r100] 147, 15. Un docteur anglais.—Ibid. 144.
[r101] 148, 1. Pour résister.—Ibid. 124.
[r102] 149, 8. Dieu dit à Moïse.—Ibid. 125.
[r103] 153, 6. Le docteur Martin Luther disait au sujet.—Ibid.
292.
[r104] 153, 11. Quand je commençai à écrire.—Ibid. 193.
[r105] 153, 22. En 1521, il vint chez moi.—Ibid. 282.
[r106] 155, 27. Maître Stiefel.—Ibid. 367.
[r107] 156, 26. Bileas.—Ibid. 192.
[r108] 157, 4. Le docteur Jeckel.—Ibid. 287.
[r109] 158, 1. Le docteur Luther faisant reproche.—Ibid. 290.
[r110] 158, 19. Des antinomiens.—Ibid. 287.
[r111] 159, 15. Qui aurait pensé.—Ibid. 288.
[r112] 160, 8. J'ai eu tant de confiance.—Ibid. 291.
[r113] 161, 1. En 1540, Luther.—Ibid. 129.
[r114] 161, 22. Maître Jobst.—Ibid. 124.
[r115] 162, 12. Si au commencement.—Ibid. 125.
[r116] 163, 4. Maître Philippe dit.—Ibid. 445.
[r117] 164, 4. Philippe me demandait.—Ibid. 29.
[r118] 164, 8. Si Philippe n'eût pas été.—Ibid. 195.
[r119] 164, 11. Le Paradis de Luther.—Ibid. 305.
[r120] 164, 21. Les paysans ne sont pas dignes.—Ibid. 52.
[r121] 164, 28. Le docteur Jonas.—Ibid. 137.
[r122] 165, 14. Un méchant et horrible.—Ibid. 70.
[r123] 165, 22. La femme du docteur.—Ibid. 150.
[r124] 166, 2. Le docteur exhortait sa femme.—Ibid.
[r125] 166, 22. Le pater noster.—Ibid. 135.
[r126] 166, 25. J'aime ma Catherine.—Ibid. 140.
[r127] 169, 3. Une jeune fille.—Ibid. 92, verso.
[r128] 169, 9. Un pasteur.—Ibid. 208.
[r129] 172, 5. Il y a des lieux.—Ibid. 212.
[r130] 172, 18. Un jour de grand orage.—Ibid. 219.
[r131] 173, 3. Suivent deux histoires.—Ibid. 214.
[r132] 173, 11. Le diable promène.—Ibid. 213.
[r133] 173, 18. Aux Pays-Bas et en Saxe.—Ibid. 221.
[r134] 173, 21. Les moines conduisaient.—Ibid. 222.
[r135] 173, 24. On racontait à table.—Ibid. 205.
[r136] 174, 8. Un vieux curé.—Ibid. 205.
[r137] 175, 14. Une autre fois, Luther.—Ibid. 205.
[r138] 176, 23. Il y avait à Erfurth.—Ibid. 215.
[r139] 177, 18. Le docteur Luc Gauric.—Ibid. 216.
[r140] 177, 21. Le diable peut se changer.—Ibid. 216.
[r141] 182, 9. Le docteur Luther devenu plus âgé.—Ibid. 222.
[r142] 182, 16. Cela m'est arrivé.—Ibid. 220.
[r143] 182, 23. Je sais, grâce à Dieu.—Ibid. 224.
[r144] 183, 9. Le Diable n'est pas.—Ibid. 202.
[r145] 183, 20. Au mois de janvier 1532.—Ukert, t. I, 320.
[r146] 184, 8. Ma maladie qui consiste.—Tischreden, 210.
[r147] 184, 13. En 1536, il maria.—Ukert, t. I, 322.
[r148] 184, 20. Pendant que le docteur Luther.—Tischreden,
229.
[r149] 185, 8. Quand le diable me trouve.—Ibid. 8.
[r150] 186, 1. La nuit, quand je me réveille.—Ibid. 218.
[r151] 186, 6. Aujourd'hui comme je.—Ibid. 220.
[r152] 186, 15. Un jour que l'on parlait à souper.—Ibid. 12.
[r153] 187, 1. Le diable me fait regarder.—Ibid. 220.
[r154] 187, 4. Le diable nous a juré.—Ibid. 362.
[r155] 187, 6. La tentation de la chair.—Ibid. 318.
[r156] 187, 13. Si je tombe.—Ibid. 226.
[r157] 187, 19. Le grain d'orge a bien à souffrir.—Ibid. 216.
[r158] 188, 15. Quand le diable vient.—Ibid. 227.
[r159] 189, 4. On peut consoler.—Ibid. 231.
[r160] 189, 10. La meilleure médecine.—Ibid. 238.
[r161] 189, 19. Préface du docteur.—Luth. Werke, t. II, 1.
[r162] 200, 3. Le mal de dents.—Tischreden, 356.
[r163] 200, 12. Un homme se plaignait.—Ibid. 357.
[r164] 201, 8. Après avoir prêché.—Ibid. 362.
[r165] 203, 3. Si j'avais su.—Ibid. 6.
[r166] 203, 8. On disait une fois.—Ibid. 5.
[r167] 203, 18. On disait un jour.—Ibid. 5, verso.
[r168] 204, 13. C'est vous qui.—Ibid. 195, verso.
[r169] 204, 15. Il sortit un jour.—Ibid. 189, verso.
[r170] 204, 17. Le 16 février.—Ibid. 414.
[r171] 204, 23. Le chancelier du comte.—Ibid. 19.
[r172] 205, 16. Dieu a un beau jeu.—Ibid. 32, verso.
[r173] 205, 22. Le monde.—Ibid. 448, verso.
[r174] 205, 26. Luther.—Ibid. 449.
[r175] 206, 15. Un des convives.—Ibid. 295.
[r176] 206, 23. Il sera si mauvais sujet.—Ibid. 15.
[r177] 207, 3. On parlait à table.—Ibid. 304. verso.
[r178] 207, 23. Pauvres gens.—Ibid. 46.
[r179] 210, 17. Je l'ai dit d'avance.—Ibid. 416.
[r180] 211, 7. La vieille électrice.—Ibid. 361-2.
[r181] 211, 15. Je voudrais.—Ibid. 147.
[r182] 211, 18. 16 février 1546.—Ibid. 362.
[r183] 211, 25. Impromptu de Luther sur la fragilité.—Ibid.
358.
[r184] 212, 19. Prédiction du Révérend.—Opera latina, Iena,
1612, Ier vol. après la table des matières.
[r185] 303, 23. Il n'y a jamais eu.—Tischreden, 243.
[r186] 304, 1. Le Pape Jules IIe du nom.—Ibid. 242.
[r187] 304, 12. Si j'avais été.—Ibid. 243.
[r188] 304, 17. Le Pape Jules II, un homme.—Ibid. 269.
[r189] 304, 23. L'an 1532.—Ibid. 341.
[r190] 305, 1. Lorsque ceux de Bruges.—Ibid. 448.
[r191] 305, 27. L'empereur Maximilien.—Ibid. 343.
[r192] 305, 22. On dit que.—Ibid. 184, verso.
[r193] 306, 22. Après l'élection.—Ibid. 53.
[r194] 307, 5. La nouvelle vint.—Ibid. 349.
[r195] 307, 14. Les rois de France.—Ibid. 349, verso.
[r196] 309, 17. Sept universités.—Ibid. 348.
[r197] 309, 23. Quelques-uns qui avaient.—Ibid. 348, verso.
[r198] 310, 3. Le duc Georges.—Ibid. 265.
[r199] 310, 7. Lorsque le duc George déclara.—Ibid. 156.
[r200] 310, 17. Le duc George a sucé.—Ibid. 313, verso.
[r201] 310, 25. Lorsque le duc George voyait.—Ibid. 142,
verso.
[r202] 312, 6. L'électeur Frédéric.—Ibid. 451, verso.
[r203] 313, 3. En 1525.—Ibid. 152.
[r204] 314, 8. On dit que l'empereur.—Ibid. 353.
[r205] 315, 6. Quoique le docteur Jonas.—Ibid. 354.
[r206] 317, 21. Après la diète.—Ibid. 156.
[r207] 319, 4. En Italie les hôpitaux.—Ibid. 145.
[r208] 320, 1. Je ne manque point.—Ibid. 424.
[r209] 320, 14. En Italie et en France.—Ibid. 281, verso.
[r210] 320, 18. En France.—Ibid. 271, verso.
[r211] 320, 25. Lorsque je vis Rome.—Ibid. 442.
[r212] 322, 1. Il y avait en Italie.—Ibid. 269, verso.
[r213] 322, 6. Un soir à la table.—Ibid. 442, verso.
[r214] 322, 15. Christoff Gross.—Ibid. 441, verso.
[r215] 323, 4. La peste règne toujours.—Ibid. 440, verso.
[r216] 324, 21. Dans mon voyage.—Ibid. 166.
[r217] 324, 25. George Siegeler.—Ibid. 184.
[r218] 325, 5. La Thuringe.—Ibid. 62.
[r219] 325, 14. L'électorat de Saxe.—Ibid. 269.
[r220] 325, 24. Le vieil électeur.—Ibid. 61, verso.
[r221] 329, Le Turc ira à Rome.—Ibid. 432.
[r222] 329, 7. Le Christ a sauvé.—Ibid. 432.
[r223] 329, 15. Qui m'eût dit.—Ibid. 436.
[r224] 329, 23. Je ne compte point.—Ibid. 436, verso.
[r225] 329, 27. Luther dit qu'après. Luth. Werke,.—Ibid. t. II.
402.

FIN DU TOME TROISIÈME.


TABLE
DU TROISIÈME VOLUME.

Livre III.—1529-1546 1
er
Chap. 1 . 1529-1532. Les Turcs.—Danger de l'Allemagne.—
Augsbourg, Smalkalde.—Danger du protestantisme. 1
Chap. II. 1534-1536. Anabaptistes de Münster. 28
Chap. III. 1536-1545. Dernières années de la vie de Luther.
—Polygamie du landgrave de Hesse, etc. 56
Livre IV.—1530-1546. 71
Chap. 1er. Conversations de Luther.—La famille, la femme,
les enfans.—La nature. 71
Chap. II. La Bible.—Les Pères.—Les scolastiques.—Le pape.
Les conciles. 85
Chap. III. Des écoles et universités et des arts libéraux. 100
Chap. IV. Drames.—Musique.—Astrologie.—Imprimerie.—
Banque, etc. 114
Chap. V. De la prédication.—Style de Luther.—Il avoue la
violence de son caractère. 123
Livre V.—Chap. 1er. Mort du père de Luther, de sa fille, etc. 131
Chap. II. De l'équité, de la Loi.—Opposition du théologien et
du juriste. 138
Chap. III. La foi; la loi. 144
Chap. IV. Des novateurs.—Mystiques, etc. 152
Chap. V. Tentations.—Regrets et doutes des amis, de la
femme; doutes de Luther lui-même. 163
Chap. VI. Le diable.—Tentations. 168
Chap. VII. Maladies.—Désir de la mort et du jugement.—
Mort, 1546. 200
Additions et Éclaircissemens. 223
Notes. 352
Renvois. 353

FIN DE LA TABLE DU TOME TROISIÈME.


ERRATA.

Page 2, ligne 12, au lieu de regardent, lisez regardant.


Page 9, ligne 21, au lieu de le mieux, lisez mieux.
Page 58, ligne 28, au lieu de théologien, lisez théologiens.
Page 252, ligne 17, au lieu de digamie, lisez bigamie.
Page 282, ligne 15, au lieu de occurences, lisez occurrences.
Page 287, ligne 10, au lieu de heureux la mère, lisez heureuse la
mère.
Page 308, ligne 10, au lieu de de Pavie, lisez à Pavie.
Page 316, ligne 1, au lieu de ça été, lisez ç'a été.
Page 317, ligne 20, au lieu de parle parle, lisez parle.
Page 327, ligne 22, au lieu de demandez, lisez demander.
Page 328, ligne 13, au lieu de ambarras, lisez embarras.

Au lecteur.
Ce livre électronique reproduit intégralement le texte original. Les erreurs
signalées par l'auteur (voir Errata) ont été corrigées. Elles sont indiquées par
(Err.) Quelques erreurs typographiques ont également été corrigées; la liste
de ces corrections se trouve ci-dessous. La ponctuation a été tacitement
corrigée par endroits.
Les notes de bas de page ont été renumérotées de 1 à 11 et regroupées à
la fin du livre. Les «Additions et éclaircissemens» ont été numérotés de a1 à
a79. Les «Renvois» ont été numérotés de r1 à r225. Additions et renvois ont
été signalés dans le texte.

Corrections.
Pages 3, 353, 355: «Cochlœus» remplacé par «Cochlæus».
Page 28: «compagnonage» remplacé par «compagnonnage» (Le mystique
compagnonnage allemand).
Page 36: «dor» par «d'or» (trente et un chevaux couverts de draps d'or).
Page 37: «cent» par «cents» (près de quatre mille deux cents).
Page 75: «de de» par «de» (Ne vous scandalisez pas de me voir).
Page 139: «barette» par «barrette» (doit ôter sa barrette devant la
théologie).
Page 209: «rassassié» remplacé par «rassasié» (On est rassasié de la parole
de Dieu).
Page 222: «sufffire» par «suffire» (que nous ayons pu y suffire).
Page 258: «deux» par «d'eux» (Que l'un d'eux avait commis un meurtre).
Page 315: «pomptement» par «promptement» (il exécute promptement).
Page 339: «Brandbourg» par «Brandebourg» (récemment introduite dans le
Brandebourg).
Page 340: «tintamare» par «tintamarre» (avec chant et tintamarre).
Page 353 «RENVOIS DU TOME TROISIÈME»: il faut sans doute lire «RENVOIS
DU TOME DEUXIÈME».
Page 360 (renvoi nº 160): ajouté «_Ibid._»
Page 361 (renvoi nº 176): au lieu de «Il sera si mauvais» il faut sans doute
lire «Il fera si mauvais»; ajouté «_Ibid._»
Page 366 Table des matières: au lieu de «TROISIÈME VOLUME» et «TOME
TROISIÈME» il faut sans doute lire «DEUXIÈME VOLUME» et «TOME
DEUXIÈME».
*** END OF THE PROJECT GUTENBERG EBOOK MÉMOIRES DE
LUTHER ÉCRITS PAR LUI-MÊME, TOME II ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG
LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and
with almost no restrictions whatsoever. You may copy it,
give it away or re-use it under the terms of the Project
Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country
where you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute


this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU AGREE
THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT
EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE
THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person
or entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you
do or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status
by the Internal Revenue Service. The Foundation’s EIN or
federal tax identification number is 64-6221541. Contributions
to the Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.

The Foundation’s business office is located at 809 North 1500


West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or determine
the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like