Tải bản đầy đủ (.pdf) (1,981 trang)

Addison wesley professional c++ primer 4th ed (2005)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.36 MB, 1,981 trang )

C++Primer,FourthEdition
ByStanleyB.Lippman,JoséeLajoie,BarbaraE.Moo
...............................................
Publisher:AddisonWesleyProfessional
PubDate:February14,2005
PrintISBN:0-201-72148-1
Pages:912

TableofContents|Index

ThispopulartutorialintroductiontostandardC++hasbeencompletelyupdated,
reorganized,andrewrittentohelpprogrammerslearnthelanguagefasteranduseitina
moremodern,effectiveway.JustasC++hasevolvedsincethelastedition,sohasthe
authors'approachtoteachingit.TheynowintroducetheC++standardlibraryfromthe
beginning,givingreadersthemeanstowriteusefulprogramswithoutfirsthavingtomaster
everylanguagedetail.Highlightingtoday'sbestpractices,theyshowhowtowrite
programsthataresafe,canbebuiltquickly,andyetofferoutstandingperformance.
Examplesthattakeadvantageofthelibrary,andexplainthefeaturesofC++,alsoshow
howtomakethebestuseofthelanguage.Asinitspreviouseditions,thebook's
authoritativediscussionoffundamentalC++conceptsandtechniquesmakesitavaluable
resourceevenformoreexperiencedprogrammers.ProgramFasterandMoreEffectively
withThisRewrittenClassicRestructuredforquickerlearning,usingtheC++standard
libraryUpdatedtoteachthemostcurrentprogrammingstylesandprogramdesign
techniquesFilledwithnewlearningaidsthatemphasizeimportantpoints,warnabout
commonpitfalls,suggestgoodprogrammingpractices,andprovidegeneralusagetips
CompletewithexercisesthatreinforceskillslearnedAuthoritativeandcomprehensiveinits
coverageThesourcecodeforthebook'sextendedexamplesisavailableontheWebatthe
addressbelow.


C++Primer,FourthEdition


ByStanleyB.Lippman,JoséeLajoie,BarbaraE.Moo
...............................................
Publisher:AddisonWesleyProfessional
PubDate:February14,2005
PrintISBN:0-201-72148-1
Pages:912

TableofContents|Index


















































Copyright
Preface
ChangestotheFourthEdition

StructureofThisBook
Acknowledgments
Chapter1.GettingStarted
Section1.1.WritingaSimpleC++Program
Section1.2.AFirstLookatInput/Output
Section1.3.AWordAboutComments
Section1.4.ControlStructures
Section1.5.IntroducingClasses
Section1.6.TheC++Program
ChapterSummary
KeytermDefinedTerms
PartI:TheBasics
Chapter2.VariablesandBasicTypes
Section2.1.PrimitiveBuilt-inTypes
Section2.2.LiteralConstants
Section2.3.Variables
Section2.4.constQualifier
Section2.5.References
Section2.6.TypedefNames
Section2.7.Enumerations
Section2.8.ClassTypes
Section2.9.WritingOurOwnHeaderFiles





















































































ChapterSummary
KeytermDefinedTerms
Chapter3.LibraryTypes
Section3.1.NamespaceusingDeclarations
Section3.2.LibrarystringType
Section3.3.LibraryvectorType
Section3.4.IntroducingIterators
Section3.5.LibrarybitsetType
ChapterSummary
KeytermDefinedTerms
Chapter4.ArraysandPointers
Section4.1.Arrays
Section4.2.IntroducingPointers
Section4.3.C-StyleCharacterStrings
Section4.4.MultidimensionedArrays
ChapterSummary

KeytermDefinedTerms
Chapter5.Expressions
Section5.1.ArithmeticOperators
Section5.2.RelationalandLogicalOperators
Section5.3.TheBitwiseOperators
Section5.4.AssignmentOperators
Section5.5.IncrementandDecrementOperators
Section5.6.TheArrowOperator
Section5.7.TheConditionalOperator
Section5.8.ThesizeofOperator
Section5.9.CommaOperator
Section5.10.EvaluatingCompoundExpressions
Section5.11.ThenewanddeleteExpressions
Section5.12.TypeConversions
ChapterSummary
KeytermDefinedTerms
Chapter6.Statements
Section6.1.SimpleStatements
Section6.2.DeclarationStatements
Section6.3.CompoundStatements(Blocks)
Section6.4.StatementScope
Section6.5.TheifStatement
Section6.6.TheswitchStatement



















































































Section6.7.ThewhileStatement
Section6.8.TheforLoopStatement
Section6.9.ThedowhileStatement
Section6.10.ThebreakStatement
Section6.11.ThecontinueStatement
Section6.12.ThegotoStatement
Section6.13.tryBlocksandExceptionHandling
Section6.14.UsingthePreprocessorforDebugging
ChapterSummary
KeytermDefinedTerms
Chapter7.Functions
Section7.1.DefiningaFunction
Section7.2.ArgumentPassing
Section7.3.ThereturnStatement
Section7.4.FunctionDeclarations
Section7.5.LocalObjects
Section7.6.InlineFunctions

Section7.7.ClassMemberFunctions
Section7.8.OverloadedFunctions
Section7.9.PointerstoFunctions
ChapterSummary
KeytermDefinedTerms
Chapter8.TheIOLibrary
Section8.1.AnObject-OrientedLibrary
Section8.2.ConditionStates
Section8.3.ManagingtheOutputBuffer
Section8.4.FileInputandOutput
Section8.5.StringStreams
ChapterSummary
KeytermDefinedTerms
PartII:ContainersandAlgorithms
Chapter9.SequentialContainers
Section9.1.DefiningaSequentialContainer
Section9.2.IteratorsandIteratorRanges
Section9.3.SequenceContainerOperations
Section9.4.HowavectorGrows
Section9.5.DecidingWhichContainertoUse
Section9.6.stringsRevisited
Section9.7.ContainerAdaptors



















































































ChapterSummary
KeytermDefinedTerms
Chapter10.AssociativeContainers
Section10.1.Preliminaries:thepairType
Section10.2.AssociativeContainers
Section10.3.ThemapType
Section10.4.ThesetType
Section10.5.ThemultimapandmultisetTypes
Section10.6.UsingContainers:Text-QueryProgram
ChapterSummary
KeytermDefinedTerms
Chapter11.GenericAlgorithms
Section11.1.Overview
Section11.2.AFirstLookattheAlgorithms
Section11.3.RevisitingIterators
Section11.4.StructureofGenericAlgorithms
Section11.5.Container-SpecificAlgorithms
ChapterSummary

KeytermDefinedTerms
PartIII:ClassesandDataAbstraction
Chapter12.Classes
Section12.1.ClassDefinitionsandDeclarations
Section12.2.TheImplicitthisPointer
Section12.3.ClassScope
Section12.4.Constructors
Section12.5.Friends
Section12.6.staticClassMembers
ChapterSummary
KeytermDefinedTerms
Chapter13.CopyControl
Section13.1.TheCopyConstructor
Section13.2.TheAssignmentOperator
Section13.3.TheDestructor
Section13.4.AMessage-HandlingExample
Section13.5.ManagingPointerMembers
ChapterSummary
KeytermDefinedTerms
Chapter14.OverloadedOperationsandConversions
Section14.1.DefininganOverloadedOperator
















































































Section14.2.InputandOutputOperators
Section14.3.ArithmeticandRelationalOperators
Section14.4.AssignmentOperators
Section14.5.SubscriptOperator
Section14.6.MemberAccessOperators
Section14.7.IncrementandDecrementOperators
Section14.8.CallOperatorandFunctionObjects
Section14.9.ConversionsandClassTypes
ChapterSummary
KeytermDefinedTerms
PartIV:Object-OrientedandGenericProgramming
Chapter15.Object-OrientedProgramming
Section15.1.OOP:AnOverview
Section15.2.DefiningBaseandDerivedClasses
Section15.3.ConversionsandInheritance
Section15.4.ConstructorsandCopyControl
Section15.5.ClassScopeunderInheritance
Section15.6.PureVirtualFunctions
Section15.7.ContainersandInheritance
Section15.8.HandleClassesandInheritance
Section15.9.TextQueriesRevisited
ChapterSummary

KeytermDefinedTerms
Chapter16.TemplatesandGenericProgramming
Section16.1.TemplateDefinitions
Section16.2.Instantiation
Section16.3.TemplateCompilationModels
Section16.4.ClassTemplateMembers
Section16.5.AGenericHandleClass
Section16.6.TemplateSpecializations
Section16.7.OverloadingandFunctionTemplates
ChapterSummary
KeytermDefinedTerms
PartV:AdvancedTopics
Chapter17.ToolsforLargePrograms
Section17.1.ExceptionHandling
Section17.2.Namespaces
Section17.3.MultipleandVirtualInheritance




ChapterSummary



KeytermDefinedTerms





























Chapter18.SpecializedToolsandTechniques
Section18.1.OptimizingMemoryAllocation
Section18.2.Run-TimeTypeIdentification
Section18.3.PointertoClassMember
Section18.4.NestedClasses
Section18.5.Union:ASpace-SavingClass
Section18.6.LocalClasses

Section18.7.InherentlyNonportableFeatures
ChapterSummary
KeytermDefinedTerms
AppendixA.TheLibrary

SectionA.1.LibraryNamesandHeaders

SectionA.2.ABriefTouroftheAlgorithms

SectionA.3.TheIOLibraryRevisited
Index


Copyright
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andthepublisherwas
awareofatrademarkclaim,thedesignationshavebeenprinted
withinitialcapitallettersorinallcapitals.
Theauthorsandpublisherhavetakencareinthepreparationof
thisbook,butmakenoexpressedorimpliedwarrantyofany
kindandassumenoresponsibilityforerrorsoromissions.No
liabilityisassumedforincidentalorconsequentialdamagesin
connectionwithorarisingoutoftheuseoftheinformationor
programscontainedherein.
Thepublisheroffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales,which
mayincludeelectronicversionsand/orcustomcoversand
contentparticulartoyourbusiness,traininggoals,marketing
focus,andbrandinginterests.Formoreinformation,please

contact:
U.S.CorporateandGovernmentSales
(800)382-3419

ForsalesoutsidetheU.S.,pleasecontact:
InternationalSales

VisitusontheWeb:www.awprofessional.com
LibraryofCongressCataloging-in-PublicationData
Lippman,StanleyB.


C++primer/StanleyB.Lippman,JoséeLajoie,BarbaraE.Moo
p.cm.
Includesindex.
ISBN0-201-72148-1(pbk.:alk.paper)
1.C++(Computerprogramlanguage)I.Lajoie,Josée.II.Moo,
QA76.73.C153L576972005
005.13'3dc22
Copyright©2005ObjectwriteInc.,JoséeLajoieandBarbaraE.
Moo
Allrightsreserved.PrintedintheUnitedStatesofAmerica.This
publicationisprotectedbycopyright,andpermissionmustbe
obtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissionin
anyformorbyanymeans,electronic,mechanical,
photocopying,recording,orlikewise.Forinformationregarding
permissions,writeto:
PearsonEducation,Inc.
RightsandContractsDepartment

OneLakeStreet
UpperSaddleRiver,NJ07458
TextprintedintheUnitedStatesonrecycledpaperatCourierin
Stoughton,Massachusetts.
Firstprinting,February2005

Dedication
ToBeth,whomakesthis,andallthings,possible.
ToDanielandAnna,whocontainvirtuallyallpossiblities.
SBL


ToMarkandMom,fortheirunconditionalloveand
support.
JL
ToAndy,whotaughtmetoprogramandsomuchmore.
BEM


Preface
C++Primer,FourthEdition,providesacomprehensive
introductiontotheC++language.Asaprimer,itprovidesa
cleartutorialapproachtothelanguage,enhancedbynumerous
examplesandotherlearningaids.Unlikemostprimers,italso
providesadetaileddescriptionofthelanguage,withparticular
emphasisoncurrentandeffectiveprogrammingtechniques.
CountlessprogrammershaveusedpreviouseditionsofC++
PrimertolearnC++.InthattimeC++hasmaturedgreatly.
Overtheyears,thefocusofthelanguageandofC++
programmershasgrownbeyondaconcentrationonrun-time

efficiencytofocusonwaysofmakingprogrammersmore
efficient.Withthewidespreadavailabilityofthestandard
library,itispossibletouseandlearnC++moreeffectivelythan
inthepast.ThisrevisionoftheC++Primerreflectsthesenew
possiblities.


ChangestotheFourthEdition
Inthisedition,wehavecompletelyreorganizedandrewritten
theC++PrimertohighlightmodernstylesofC++
programming.Thiseditiongivescenterstagetousingthe
standardlibrarywhiledeemphasizingtechniquesforlow-level
programming.Weintroducethestandardlibrarymuchearlierin
thetextandhavereformulatedtheexamplestotakeadvantage
oflibraryfacilities.Wehavealsostreamlinedandreorderedthe
presentationoflanguagetopics.
Inadditiontorestructuringthetext,wehaveincorporated
severalnewelementstoenhancethereader'sunderstanding.
EachchapterconcludeswithaChapterSummaryandglossary
ofDefinedTerms,whichrecapthechapter'smostimportant
points.Readersshouldusethesesectionsasapersonal
checklist:Ifyoudonotunderstandaterm,restudythe
correspondingpartofthechapter.
We'vealsoincorporatedanumberofotherlearningaidsinthe
bodyofthetext:
Importanttermsareindicatedinbold;importantterms
thatweassumearealreadyfamiliartothereaderare
indicatedinbolditalics.Eachtermappearsinthe
chapter'sDefinedTermssection.
Throughoutthebook,wehighlightpartsofthetexttocall

attentiontoimportantaspectsofthelanguage,warnabout
commonpitfalls,suggestgoodprogrammingpractices,and
providegeneralusagetips.Wehopethatthesenoteswill
helpreadersmorequicklydigestimportantconceptsand
avoidcommonpitfalls.
Tomakeiteasiertofollowtherelationshipsamongfeatures


andconcepts,weprovideextensiveforwardandbackward
cross-references.
Wehaveprovidedsidebardiscussionsthatfocuson
importantconceptsandsupplyadditionalexplanationsfor
topicsthatprogrammersnewtoC++oftenfindmost
difficult.
Learninganyprogramminglanguagerequireswriting
programs.Tothatend,theprimerprovidesextensive
examplesthroughoutthetext.Sourcecodeforthe
extendedexamplesisavailableontheWebatthefollowing
URL:
/>Whathasn'tchangedfromearlierversionsisthatthebook
remainsacomprehensivetutorialintroductiontoC++.Our
intentistoprovideaclear,completeandcorrectguidetothe
language.Weteachthelanguagebypresentingaseriesof
examples,which,inadditiontoexplaininglanguagefeatures,
showhowtomakethebestuseofC++.Althoughknowledgeof
C(thelanguageonwhichC++wasoriginallybased)isnot
assumed,wedoassumethereaderhasprogrammedina
modernblock-structuredlanguage.



StructureofThisBook
C++PrimerprovidesanintroductiontotheInternational
StandardonC++,coveringboththelanguageproperandthe
extensivelibrarythatispartofthatstandard.Muchofthe
powerofC++comesfromitssupportforprogrammingwith
abstractions.LearningtoprogrameffectivelyinC++requires
morethanlearningnewsyntaxandsemantics.Ourfocusison
howtousethefeaturesofC++towriteprogramsthataresafe,
thatcanbebuiltquickly,andyetofferperformancecomparable
tothesortsoflow-levelprogramsoftenwritteninC.
C++isalargelanguageandcanbedauntingtonewusers.
ModernC++canbethoughtofascomprisingthreeparts:
Thelow-levellanguage,largelyinheritedfromC
Moreadvancedlanguagefeaturesthatallowustodefine
ourowndatatypesandtoorganizelarge-scaleprograms
andsystems
Thestandardlibrary,whichusestheseadvancedfeaturesto
provideasetofusefuldatastructuresandalgorithms
MosttextspresentC++inthissameorder:Theystartby
coveringthelow-leveldetailsandthenintroducethethemore
advancedlanguagefeatures.Theyexplainthestandardlibrary
onlyafterhavingcoveredtheentirelanguage.Theresult,all
toooften,isthatreadersgetboggeddowninissuesoflow-level
programmingorthecomplexitiesofwritingtypedefinitionsand
neverreallyunderstandthepowerofprogramminginamore
abstractway.Needlesstosay,readersalsooftendonotlearn
enoughtobuildtheirownabstractions.


Inthiseditionwetakeacompletelydifferenttack.Westartby

coveringthebasicsofthelanguageandthelibrarytogether.
Doingsoallowsyou,thereader,towritesignificantprograms.
Onlyafterathoroughgroundinginusingthelibraryandwriting
thekindsofabstractprogramsthatthelibaryallowsdowemove
ontothosefeaturesofC++thatwillenableyoutowriteyour
ownabstractions.
PartsIandIIcoverthebasiclanguageandlibraryfacilities.The
focusofthesepartsistolearnhowtowriteC++programsand
howtousetheabstractionsfromthelibrary.MostC++
programmersneedtoknowessentiallyeverythingcoveredin
thisportionofthebook.
InadditiontoteachingthebasicsofC++,thematerialinParts
IandIIservesanotherimportantpurpose.Thelibraryfacilities
arethemselvesabstractdatatypeswritteninC++.Thelibrary
canbedefinedusingthesameclass-constructionfeaturesthat
areavailabletoanyC++programmer.Ourexperiencein
teachingC++isthatbyfirstusingwell-designedabstracttypes,
readersfinditeasiertounderstandhowtobuildtheirown
types.
PartsIIIthroughVfocusonhowwecanwriteourowntypes.
PartIIIintroducestheheartofC++:itssupportforclasses.
Theclassmechanismprovidesthebasisforwritingourown
abstractions.Classesarealsothefoundationforobject-oriented
andgenericprogramming,whichwecoverinPartIV.The
PrimerconcludeswithPartV,whichcoversadvancedfeatures
thatareofmostuseinstructuringlarge,complexsystems.


Acknowledgments
AsinpreviouseditionsofthisPrimer,we'dliketoextendour

thankstoBjarneStroustrupforhistirelessworkonC++and
forhisfriendshiptotheseauthorsthroughoutmostofthattime.
We'dalsoliketothankAlexStepanovforhisoriginalinsights
thatledtothecontainersandalgorithmsthatformthecoreof
thestandardlibrary.Finally,ourthanksgototheC++
Standardscommitteemembersfortheirhardworkinclarifying,
refining,andimprovingC++overmanyyears.
Wealsoextendourdeep-feltthankstoourreviewers,whose
helpfulcommentsonmultipledraftsledustomake
improvementsgreatandsmallthroughoutthebook:Paul
Abrahams,MichaelBall,MaryDageforde,PaulDuBois,Matt
Greenwood,MatthewP.Johnson,AndrewKoenig,NevinLiber,
BillLocke,RobertMurray,PhilRomanik,JustinShaw,Victor
Shtern,ClovisTondo,DaveedVandevoorde,andSteveVinoski.
ThisbookwastypesetusingLATEXandthemanypackagesthat
accompanytheLATEXdistribution.Ourwell-justifiedthanksgo
tothemembersoftheLATEXcommunity,whohavemade
availablesuchpowerfultypesettingtools.
TheexamplesinthisbookhavebeencompiledontheGNUand
Microsoftcompilers.Ourthankstotheirdevelopers,andto
thosewhohavedevelopedalltheotherC++compilers,thereby
makingC++areality.
Finally,wethankthefinefolksatAddison-Wesleywhohave
shepherdedthiseditionthroughthepublishingprocess:Debbie
Lafferty,ouroriginaleditor,whoinitiatedthiseditionandwho
hadbeenwiththePrimerfromitsveryfirstedition;Peter
Gordon,ourneweditor,whoseinsistenceonupdatingand
streamliningthetexthave,wehope,greatlyimprovedthe
presentation;KimBoedigheimer,whokeepsusallonschedule;



andTyrrellAlbaugh,JimMarkham,ElizabethRyan,andJohn
Fuller,whosawusthroughthedesignandproductionprocess.


Chapter1.GettingStarted
CONTENTS

Section1.1WritingaSimpleC++Program

2

Section1.2AFirstLookatInput/Output

5

Section1.3AWordAboutComments

10

Section1.4ControlStructures

11

Section1.5IntroducingClasses

20

Section1.6TheC++Program


25

ChapterSummary

28

DefinedTerms

28

ThischapterintroducesmostofthebasicelementsofC++:
built-in,library,andclasstypes;variables;expressions;
statements;andfunctions.Alongtheway,we'llbrieflyexplain
howtocompileandexecuteaprogram.
Havingreadthischapterandworkedthroughtheexercises,the
readershouldbeabletowrite,compile,andexecutesimple
programs.Subsequentchapterswillexplaininmoredetailthe
topicsintroducedhere.
Learninganewprogramminglanguagerequireswriting
programs.Inthischapter,we'llwriteaprogramtosolvea


simpleproblemthatrepresentsacommondata-processing
task:Abookstorekeepsafileoftransactions,eachofwhich
recordsthesaleofagivenbook.Eachtransactioncontainsan
ISBN(InternationalStandardBookNumber,auniqueidentifier
assignedtomostbookspublishedthroughouttheworld),the
numberofcopiessold,andthepriceatwhicheachcopywas
sold.Eachtransactionlookslike
0-201-70353-X424.99


wherethefirstelementistheISBN,thesecondisthenumber
ofbookssold,andthelastisthesalesprice.Periodicallythe
bookstoreownerreadsthisfileandcomputesthenumberof
copiesofeachtitlesold,thetotalrevenuefromthatbook,and
theaveragesalesprice.Wewanttosupplyaprogramdothese
computations.
Beforewecanwritethisprogramweneedtoknowsomebasic
featuresofC++.Ataminimumwe'llneedtoknowhowto
write,compile,andexecuteasimpleprogram.Whatmustthis
programdo?Althoughwehavenotyetdesignedoursolution,
weknowthattheprogrammust
Definevariables
Doinputandoutput
Defineadatastructuretoholdthedatawe'remanaging
TestwhethertworecordshavethesameISBN
Writealoopthatwillprocesseveryrecordinthetransaction
file


We'llstartbyreviewingthesepartsofC++andthenwritea
solutiontoourbookstoreproblem.


1.1.WritingaSimpleC++Program
EveryC++programcontainsoneormorefunctions,oneof
whichmustbenamedmain.Afunctionconsistsofasequenceof
statementsthatperformtheworkofthefunction.The
operatingsystemexecutesaprogrambycallingthefunction
namedmain.Thatfunctionexecutesitsconstituentstatements

andreturnsavaluetotheoperatingsystem.
Hereisasimpleversionofmaindoesnothingbutreturnavalue:
intmain()
{
return0;
}

Theoperatingsystemusesthevaluereturnedbymainto
determinewhethertheprogramsucceededorfailed.Areturn
valueof0indicatessuccess.
Themainfunctionisspecialinvariousways,themostimportant
ofwhicharethatthefunctionmustexistineveryC++program
anditisthe(only)functionthattheoperatingsystemexplicitly
calls.
Wedefinemainthesamewaywedefineotherfunctions.A
functiondefinitionspecifiesfourelements:thereturntype,the
functionname,a(possiblyempty)parameterlistenclosedin
parentheses,andthefunctionbody.Themainfunctionmay
haveonlyarestrictedsetofparameters.Asdefinedhere,the
parameterlistisempty;Section7.2.6(p.243)willcoverthe
otherparametersthatcanbedefinedformain.
Themainfunctionisrequiredtohaveareturntypeofint,which


isthetypethatrepresentsintegers.Theinttypeisabuilt-in
type,whichmeansthatthetypeisdefinedbythelanguage.
Thefinalpartofafunctiondefinition,thefunctionbody,isa
blockofstatementsstartingwithanopencurlybraceand
endingwithaclosecurly:
{

return0;
}

Theonlystatementinourprogramisareturn,whichisa
statementthatterminatesafunction.
Notethesemicolonattheendofthereturnstatement.
SemicolonsmarktheendofmoststatementsinC++.
Theyareeasytooverlook,butwhenforgottencanleadto
mysteriouscompilererrormessages.

Whenthereturnincludesavaluesuchas0,thatvalueisthe
returnvalueofthefunction.Thevaluereturnedmusthavethe
sametypeasthereturntypeofthefunctionorbeatypethat
canbeconvertedtothattype.Inthecaseofmainthereturn
typemustbeint,andthevalue0isanint.
Onmostsystems,thereturnvaluefrommainisastatus
indicator.Areturnvalueof0indicatesthesuccessfulcompletion
ofmain.Anyotherreturnvaluehasameaningthatisdefinedby
theoperatingsystem.Usuallyanonzeroreturnindicatesthat
anerroroccurred.Eachoperatingsystemhasitsownwayof


tellingtheuserwhatmainreturned.

1.1.1.CompilingandExecutingOurProgram
Havingwrittentheprogram,weneedtocompileit.Howyou
compileaprogramdependsonyouroperatingsystemand
compiler.Fordetailsonhowyourparticularcompilerworks,
you'llneedtocheckthereferencemanualoraska
knowledgeablecolleague.

ManyPC-basedcompilersarerunfromanintegrated
developmentenvironment(IDE)thatbundlesthecompilerwith
associatedbuildandanalysistools.Theseenvironmentscanbe
agreatassetindevelopingcomplexprogramsbutrequireafair
bitoftimetolearnhowtouseeffectively.Mostofthese
environmentsincludeapoint-and-clickinterfacethatallowsthe
programmertowriteaprogramandusevariousmenusto
compileandexecutetheprogram.Learninghowtousesuch
environmentsiswellbeyondthescopeofthisbook.
Mostcompilers,includingthosethatcomewithanIDE,provide
acommand-lineinterface.Unlessyouarealreadyfamiliarwith
usingyourcompiler'sIDE,itcanbeeasiertostartbyusingthe
simpler,command-lineinterface.Usingthecommand-line
interfaceletsyouavoidtheoverheadoflearningtheIDEbefore
learningthelanguage.

ProgramSourceFileNamingConvention
Whetherweareusingacommand-lineinterfaceoranIDE,
mostcompilersexpectthattheprogramwewanttocompilewill
bestoredinafile.Programfilesarereferredtoassourcefiles.
Onmostsystems,asourcefilehasanamethatconsistsoftwo
parts:afilenameforexample,prog1andafilesuffix.By
convention,thesuffixindicatesthatthefileisaprogram.The


suffixoftenalsoindicateswhatlanguagetheprogramiswritten
inandselectswhichcompilertorun.Thesystemthatweused
tocompiletheexamplesinthisbooktreatsafilewithasuffixof
.ccasaC++programandsowestoredthisprogramas
prog1.cc


ThesuffixforC++programfilesdependsonwhichcompiler
you'rerunning.Otherconventionsinclude
prog1.cxx
prog1.cpp
prog1.cp
prog1.C


InvokingtheGNUorMicrosoftCompilers
ThecommandusedtoinvoketheC++compilervariesacrosscompilers
andoperatingsystems.ThemostcommoncompilersaretheGNU
compilerandtheMicrosoftVisualStudiocompilers.Bydefaultthe
commandtoinvoketheGNUcompilerisg++:
$g++prog1.cc-oprog1

where$isthesystemprompt.Thiscommandgeneratesanexecutable
filenamedprog1orprog1.exe,dependingontheoperatingsystem.On
UNIX,executablefileshavenosuffix;onWindows,thesuffixis.exe.The
-oprog1isanargumenttothecompilerandnamesthefileinwhichtoput
theexecutablefile.Ifthe-oprog1isomitted,thenthecompilergenerates
anexecutablenameda.outonUNIXsystemsanda.exeonWindows.
TheMicrosoftcompilersareinvokedusingthecommandcl:
C:\directory>cl-GXprog1.cpp

whereC:directory>isthesystempromptanddirectoryisthenameofthe
currentdirectory.Thecommandtoinvokethecompileriscl,and-GXis
anoptionthatisrequiredforprogramscompiledusingthecommandlineinterface.TheMicrosoftcompilerautomaticallygeneratesan
executablewithanamethatcorrespondstothesourcefilename.The
executablehasthesuffix.exeandthesamenameasthesourcefile

name.Inthiscase,theexecutableisnamedprog1.exe.
Forfurtherinformationconsultyourcompiler'suser'sguide.

RunningtheCompilerfromtheCommandLine
Ifweareusingacommand-lineinterface,wewilltypically
compileaprograminaconsolewindow(suchasashellwindow
onaUNIXsystemoraCommandPromptwindowonWindows).
Assumingthatourmainprogramisinafilenamedprog1.cc,we


×