Programming Principles and Practice Using C 1st Edition Bjarne Stroustrup instant download
Programming Principles and Practice Using C 1st Edition Bjarne Stroustrup instant download
https://ebookname.com/product/programming-principles-and-
practice-using-c-1st-edition-bjarne-stroustrup/
https://ebookname.com/product/object-oriented-programming-using-
c-fourth-edition-joyce-farrell/
https://ebookname.com/product/programming-fundamentals-a-modular-
structured-approach-using-c-kenneth-leroy-busbee/
https://ebookname.com/product/goddess-traditions-in-tantric-
hinduism-history-practice-and-doctrine-1st-edition-bjarne-
wernicke-olesen-editor/
https://ebookname.com/product/an-introduction-to-political-
philosophy-1st-edition-alexander-rainy-maclean-murray/
Democratic Theorizing from the Margins 1st Edition
Marla Brettschneider
https://ebookname.com/product/democratic-theorizing-from-the-
margins-1st-edition-marla-brettschneider/
https://ebookname.com/product/working-with-dreams-initiation-
into-the-soul-s-speaking-about-itself-1st-edition-wolfgang-
giegerich/
https://ebookname.com/product/syntax-a-functional-typological-
introduction-volume-ii-talmy-givon/
https://ebookname.com/product/making-the-british-
empire-1660-1800-1st-edition-jason-peacey/
https://ebookname.com/product/the-introduction-to-the-magee-
system-of-technical-analysis-2nd-edition-w-h-c-bassetti/
Encyclopedia of law enforcement 1st Edition Larry E.
Sullivan
https://ebookname.com/product/encyclopedia-of-law-
enforcement-1st-edition-larry-e-sullivan/
Programming
Programming
Principles and Practice
Using C++
Bjarne Stroustrup
./.,· Addison-Wesley
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • Madrid
Capetown • Sydney • Tokyo • Singapore • Mexico City
Many of the designations used by manufacturers and sellers to distinguish their products arc claimed as
trademarks. Where those designations appear in this book. and tl1c publisher was aware of a trademark
claim, the designations have been primed witl1 initial capital letters or in all capitals.
The author and publisher have taken care in the preparation of this book, but make no expressed or im·
plied warran t y of any kind and assume no responsibility for errors or omissioru. No liability is assumed
for incidental or consequential damages in connection witl1 or arising out of the usc of the information or
programs contained herein.
The publisher offers excellent discounts on tllis book when ordered in quantity for bulk purcl!ases or spe
cial sales, wllich may include electronic versions and/or custom covers and content particular to your busi
ness. training goals. marketing focus. and branding interests. For more information. please contact:
International Sales
intcmational@pearsoncd.com
Stroustrup, Bjame.
Programming principles and practice using C++ I Bjamc Stroustrup.
P· em.
Includes bibliographical references and index.
ISBN 978-0-321-54372·1 (pbk. : alk. paper) I. C++ (Computer program language) I. Title.
QA76.73.C153S82 2008
005.13'3-dc22
2008032595
AU rights reserved. Printed in the United States of America. ll1is publication is protected by copyright, and
permission must be obtained from tl1c publisher prior to any prohibited reproduction, storage in a retrieval
system, or transmission in any form or by any means. electronic, mechanical, photocopying, recording, or
likewise. For information regarding pemlissions, write to:
ISBN-13: 978·0·321·54372·1
ISBN-10: 0-321-54372·6
Text printed in the United States on recycled paper at Courier in Kendallville, Indiana.
Ftrst printing, December 2008
Contents
Preface xxiii
Chapter 0 Notes to the Reader
0.1 The structure of this book 2
0.1. 1 General approach 3
0.1.2 Drills, exercises, etc. 4
0.1.3 What comes after this book? 5
0.2 A philosophy of teaching and learning 6
0.2.1 The order of topics 9
0.2.2 Programming and programming language 10
0.2.3 Portability 11
0.3 Programming and computer science 12
0.4 Creativity and problem solving 12
0.5 Request for feedback 12
0.6 References 13
0.7 Biographies 14
Bjame Stroustrup 14
Lawrence "Pete" Petersen 15
"
vi CONTENTS
2. 1 Programs 44
2.2 T he classic first program 45
2.3 Compilation 47
2.4 Linking 51
2.5 Programming environments 52
Chapter 4 Computation 89
4.1 Computation 90
4.2 Objectives and tools 92
CONTENTS vii
4.3 Expressions 94
4.3.1 Constant expressions 95
4.3.2 Operators 96
4.3.3 Conversions 98
4.4 Statements 99
4.4.1 Selection 101
4.4.2 Iteration 108
4.5 Functions 1 12
4.5.1 Why bother with functions? 114
4.5.2 Function declarations 115
4.6 Vector 1 16
4.6.1 Growing a vector 118
4.6.2 A numeric example 119
4 .6.3 A text example 121
4.7 Language features 123
Chapter 5 Errors 1 31
5. 1 Introduction 132
5.2 Sources of errors 134
5.3 Compile-time errors 134
5.3.1 Syntax errors 135
5.3.2 Type errors 136
.5.3.3 Non-errors 137
5.4 Link-time errors 137
5.5 Run-time errors 138
5.5.1 T he caller deals with errors 140
5.5.2 l11e callee deals with errors 141
5.5.3 Error reporting 143
5.6 Exceptions 144
5.6.1 Bad arguments 145
5.6.2 Range errors 146
5.6.3 Bad input 148
5.6.4 Narrowing errors 151
5.7 Logic errors 152
5.8 Estimation 155
5.9 Debugging 156
5.9.1 Practical debug advice 1S7
5. 10 Pre- and post-conditions 161
5.10.1 Post·conditions 163
5. 1 1 Testing 164
viii CONTENTS
Glossary 1171
Bibliography 1177
Index 1181
Preface
-Admiral Farragut
xxiii
xxiv PREFACE
Why would you want to program? Our civilization runs on software. With·
out understanding software you are reduced to believing in "magic" and will be
locked out of many of the most interesting, profitable, and socially useful techni
cal fields of work. When I talk about programming, I think of the whole spec
trum of computer programs from personal computer applications with G Uls
(graphical user interfaces), through engineering calculations and embedded sys
tems control applications (such as digital cameras, cars, and cell phones), to text
manipulation applications as found in many humanities and business applica
tions. Like mathematics, programming- when done well- is a valuable intellec
tual exercise that sharpens our ability to think. However, thanks to feedback
from the computer, programming is more concrete than most forms of math, and
therefore accessible to more people. It is a way to reach out and change the world
- ideally for the better. Finally, programming can be great fun.
W hy C++? You can't learn to program without a progranmung language,
and C++ directly supports the key concepts and techniques used in real-world
software. C++ is one of the most widely used programming languages, found in
an unsurpassed range of application areas. You fmd C++ applications every·
where from the bottom of the oceans to the surface of Mars. C++ is precisely
and comprehensively defmed by a nonproprietary international standard. Qyal·
ity and/or free implementations are available on every kind of computer. Most of
the programming concepts that you will learn using C++ can be used directly in
other languages, such as C, C#, Fortran, andjava. Fmally, I simply like C++ as
a language for writing elegant and efficient code.
This is not the easiest book on beginning programming; it is not meant to
be. I just aim for it to be the easiest book from which you can learn the basics of
real-world programming. That's quite an ambitious goal because much modern
software relies on techniques considered advanced just a few years ago.
My fundamental assumption is that you want to write programs for the use
of others, and to do so responsibly, providing a decent level of system quality:
that is, I assume that you want to achieve a level of professionalism. Consc·
quently, I chose the topics for this book to cover what is needed to get started
with real-world programming. not just what is easy to teach and learn. If you
need a technique to get basic work done right, I describe it. demonstrate concepts
and language facilities needed to support the technique, provide exercises for it,
and expect you to work on those exercises. If you just want to understand toy
programs, you can get along with far less than I present. On the other hand, I
won't waste your time with material of marginal practical importance. If an idea
is explained here, it's because you'll almost certainly need it.
If your desire is to use the work of others without understanding how things
arc done and witl10ut adding significantly to the code yourself, tills book is not
for you. If so, please consider whether you would be better served by another
book and another language. If that is approximately your view of programming,
please also consider from where you got that view and whether it in fact is adc·
quate for your needs. People often underestimate the complexity of program-
Exploring the Variety of Random
Documents with Different Content
room, whose peculiar form or colour had attracted his attention? he
thinks nothing of taking the life of any thing he admires. Oh! it turns
me sick to think of it; had I flown one inch farther I might have been
thus impaled, and you also; no doubt you would not have escaped
his observation, and for the sake of your sting, or examining what
you carry your honey in, you would have been quickly dispatched;
various are the instruments he has got about him, and numberless
insects does he daily destroy."
"These are detestable creatures indeed," answered the Bee; "what
can't they be satisfied with viewing our forms as we pass along, but
must they pull us to pieces, by way of admiration? I fancy when they
have taken the most accurate survey, they could not make either a
Bee, or a Butterfly; it is a pity therefore that they should destroy that
life which they can never give. I declare the more I see of these
human beings, and think of their cruelty, as well as absurdities, it
makes me almost determine to quit the haunts of men, and if it ever
should be my lot again to seek another habitation, I would use all
my influence with my fellow Bees in order to remove to some wild
wood where they might never find us."
"You would be perfectly right," returned the Butterfly; "as for us, if
we escape them one summer, we willingly resign our lives at the end
of it, and led by instinct seek a place in which we die unlamented,
and soon forgotten; but this is not the case with you; while you live
you are useful, and at your death a whole society feels your loss; but
look," continued he, pointing towards a bottle that hung tied to the
branch of a fruit-tree, in which were several wasps decoyed thither
by the liquid it contained, and dying in the sweets they sought,
"there is another instance of their malice, don't you see those poor
creatures?"
"Oh! yes," returned the Bee, "and though I am no friend to wasps,
who are often wishing to share the fruits of our labour, without
having any right to them; and in many things are striving to imitate
us, though I believe their chief aim is to do mischief, yet I cannot
justify men who use such mean arts to entrap them to their
destruction; but what is that I see in yonder window?" continued he
with a hurried air, "something that more particularly demands my
attention, a Bee in distress; and hark, he calls to me for assistance;"
so saying, without waiting for the Butterfly to accompany him, he
flew towards the place, where was a Bee nearly drowning in a pot of
honey. "And one of my own hive too!" exclaimed he, as he drew
nearer; "my dear brother, how came you in such a situation?"
"Surely we are to see nothing but shocking sights to-day," observed
the compassionate Butterfly, who had hastily followed his friend, half
afraid that something still more terrible had happened, "but," said
he, on seeing the struggling captive, "he will not die; 'tis certain he
can keep his head above the edge till you have procured more
assistance; I fear I am not strong enough to help to pull him out."
While he was speaking, his companion had flown to the hive, and
with incredible swiftness returned with more of the community, who
altogether lent their aid, and after much toil and pains extricated the
poor exhausted Bee from the ill effects of seeking too large a share
of those sweets which only proved so, when moderately enjoyed,
'safe in themselves but dangerous in the excess.'
"I only rested on the edge of the pan," said he, as soon as he could
speak, "and after an unsuccessful flight was glad to see a store of
that which I had been so long searching for in vain; I thought I
would just take a sip or two, and perhaps bring home a little of it to
the hive."
On hearing this one of the oldest of the throng thus addressed him:
"Know, my brother, that what we make ourselves is only welcome
there, and that food for which we labour hardest, is the sweetest to
the palate of every industrious Bee; idle drones and wandering
wasps may sip the honey which others have prepared, but let the
danger you have escaped to-day teach you to use the powers nature
has given you, and taste the sweets of your own procuring rather
than that of others."
The trembling Bee thanked him for his advice, and promising to
follow it, he was escorted home by all the train, where he met with
other assistants, who cleared away the clammy substance that still
encumbered him, and he was suffered to rest within all that day to
recover himself. Meanwhile, the Butterfly waited without the hive, till
his friend returned, and they renewed their flight.
Nothing particular met their eye till they passed some flies, who
were round a piece of horse-flesh, the smell of which discovered
where it lay, and its half devoured state shewed the avidity with
which these buzzing insects fed upon it. "See," said the Bee, "what
opposite natures are within the circle of creation. These devouring
flies find as much pleasure in eating from this stinking carrion, as
from the choicest honey; nay, perhaps this is more agreeable to
them, though nothing in which they can thrust their devouring
trunks escapes their taste, but with this delicious morsel, that really
poisons the surrounding air, they are so delighted, that they even
chuse it for an habitation likewise. Here they lay their eggs, and
bring forth their young, and having no trouble to hunt for food for
them, they spend their time in flying round it, till their habitation and
provision being gone together, they are obliged to seek another
residence equally convenient. Though you bear the same name, my
friend," continued he, "I am witness that you have not their nature."
"Their nature!" interrupted the Butterfly, half offended at being
mentioned together, "no! I hope not, or their name either! what,
shall the beautiful winged tribe of Butterflies be put upon a footing
with these carrion-eaters, who live upon what, even in our crawling
state, we should reject with disgust. If I may speak my opinion, I
think their form, and the noise they make while flying, is more like
your race than ours, though alas! in one respect, I feel myself too
closely allied to them, that is, I must shortly resign my being; the
date of my life will soon be ended; I have felt the chilling blast of the
morning air long before you are out of your hive, and if you are not
already aware of it, can give you notice that winter is approaching."
"Indeed," replied the Bee, "I have seen some tokens of it myself; the
flowers are not in such plenty, and as their faded leaves fall off, no
young buds are seen to supply their place; however, such is the use
which we have made of the summer, that we are not afraid to look
forward to the time when every outward resource shall fail: but, my
friend, I fear you are of too delicate a frame to live through the
winter, though the place of your retreat be ever so warm; but have
you not thought of where you will retire to?" continued he.
"A place to die in is easily found," replied the Butterfly, "and you
must not be surprised if you see me no more; the damps of the
night will soon prove fatal, and I know not if I shall survive another."
"Do not speak so," returned the Bee, "how gladly would I afford you
an asylum if it was in my power; however, I cannot let you resign
your life so easily; green leaves are yet to be found, and now, within
our reach, I see a convenient crevice, into which you may creep;
there cherish life as long as you can, my friend, and by only
venturing out when the sun shines brightly, you may perhaps extend
your days beyond their usual period, and have your name recorded,
as a Butterfly who has survived the summer."
"Thank your kindness," returned the short-lived insect, "my life has
been already lengthened through your means, but you cannot
renovate my nature; may yours be extended."
"As long as it can be useful," said the Bee, interrupting him, "but to
you I owe all that I have gathered this summer," added he; "for had
it not been for your friendly and compassionate encouragement
when first we met, I should have sunk a victim to the consciousness
of deserved destruction; say not, therefore, that you have been of
no use in the world."
"I will not," returned the Butterfly, faintly fluttering his wings, as if
with his last breath he was desirous of rejoicing it had been in his
power to do good.
From this time the poor Butterfly was still more sensible of the
weakness of his frame, and flying towards the place his friend had
pointed out, he entered, never to quit it more, "self-buried 'ere he
died," for in the morning when the Bee visited the spot he was deaf
to his voice, and his pitying friend had to lament the sudden change
in one he had so very lately seen frisking about in all the gaiety of
health and spirits.
"Poor fly," said he, "thou hast been faithful to me, and has even
forgot thy wonted pleasures to afford me assistance; I will not leave
thee to the devouring jaws of thy fellow insects, at least thy little
body shall be preserved from being so destroyed," and with this
resolution he spent one whole day in gathering wax, and stopping
up the crevice which contained the remains of his friend—all the
return he could now make for his former kindness. After having
given this last proof of affection, he returned to the hive, and there
in the busy labors of the Commonwealth soon forgot the shock
which the unexpected death of his airy companion had occasioned.
During that winter they were suffered to remain unmolested, and as
the ensuing summer approached, (according to the plan he had
formed so long ago,) he proposed their taking a farther flight, and
seeking a refuge in some solitary wood; "I have seen more of
mankind than you have, my friends," said he, "and have observed
both their customs and manners; believe me, they are inconsistent
fickle creatures; their conduct towards one another shows that they
are not to be trusted; much more, then, have we reason to be afraid
of them. You very well know it is in our power to live without their
assistance; what is it which they procure us but just an empty shell
for our habitation? for this they expect our stock of honey, and to
obtain it scruple not to take our lives! We have already seen, in the
destruction of one or two of our neighbouring hives, the fate which
awaits us; but could I persuade all of my species to wing their flight
beyond their reach, they might be taught a little more humanity, and
would perhaps spare our lives, if we were again in their power.
Content to share with us what our labours have produced, they
might then leave us to die when our exhausted nature fails, and for
their own sakes also would not cut us off in the prime of life, and
while we have health and strength to add to the stock, which would
be as much for their benefit as our own."
This speech had the desired effect; the whole community seemed
roused by it, and entering into his scheme, on the appointed day not
a Bee was left behind, but altogether mounting the air they winged
their flight far beyond its usual extent, nor could all the clattering of
pots and kettles make them settle, till clear of the noise and out of
the sight of man they found an habitation for themselves, and under
the covert of a thick wood passed the remainder of their days in
peaceful industry.
THE END.
TRANSCRIBER'S NOTES
Obvious spelling, typographical and punctuation errors have been corrected after careful
comparison with other occurrences within the text and consultation of external sources.
Moved 'CHAP VI' heading in Chapter Summary section from incorrect place to before 'The
Bees swarm' Pg vii
Spacing retained in 'every where' Pg 26 and 'every thing' Pg 34
Spacing retained in 'well known' Pg 48
Spacing retained in 'any thing' Pg 65
Added missing end quotes; 'been feeding,' to 'been feeding,"' Pg 28
Added missing end quotes, 'no longer friends.' to 'no longer friends."' Pg 67
Added missing second end quotes, 'a toast, Sir?"' to 'a toast, Sir?""' Pg 89
Added missing end quotes, 'creature disagreeable?' to 'creature disagreeable?"' Pg 106
Added missing start quotes, 'I never' to '"I never' Pg 46
Removed bad quotes, 'hurting him:"' to 'hurting him:' Pg 46
Removed bad quotes, '"Though you bear' to 'Though you bear' Pg 125
Added missing end and start quotes, '"Oh! said he, I' to '"Oh!" said he, "I' Pg 73
Typo; changed 'laid' to 'said' Pg 29
Typo; changed 'littles' to 'little' Pg 42
Typo; changed 'flowers' to 'flower' Pg 47
Typo; changed 'gardon' to 'garden' Pg 65
Typo; changed 'surservient' to 'subservient' Pg 70
Typo; changed 'Bee,' to 'Bee.' Pg 72
Typo; changed 'he weapons' to 'the weapons' Pg 83
Archaic use of 'an' before 'h' retained; for example 'an humble' Pg 50 et al.
Archaic spelling of 'chace', 'chaced' and 'chacing' retained Pg 44 et al.
Archaic spelling of 'aukward' retained Pg 64
Archaic spelling of 'taylor' retained Pg 74
Archaic spelling of 'incumbered' and 'incumbrance' retained; one occurrence of
'encumbered' also retained Pg 19 et al.
Archaic spelling of 'chuse' retained; one occurrence of 'choose' in preface also retained Pg
113 et al.
Archaic spelling of 'fixt' retained; one occurrence of 'fixed' also retained Pg 92 et al.
Archaic spelling of 'encrease' and 'encreased' retained; three occurrences of 'increase'
etc. also retained Pg 52 et al.
Archaic spelling of 'gayly drest' retained Pg 106
*** END OF THE PROJECT GUTENBERG EBOOK THE
PERAMBULATIONS OF A BEE AND A BUTTERFLY, ***
Updated editions will replace the previous one—the old editions will
be renamed.
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.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.
• 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 comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
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.
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.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com