《Practical C Programming (Nutshell Handbook)》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
PracticalC++ProgrammingSteveOuallineO'Reilly&Associates,Inc.Beijing·Cambridge·Köln·Paris·Sebastopol·Taipei·TokyoPageivPracticalC++ProgrammingbySteveOuallineCopyright©1995O'Reilly&Associates,Inc.Allrightsreserved.PrintedintheUnitedStatesofAmerica.Editors:AdrianNyeandDaleDoughertyProductionEditor:NicoleGipsonPrintingHistory:August1995FirstEdition.January1997:Minorcorrections.NutshellHandbook,theNutshellHandbooklogo,andtheO'ReillylogoareregisteredtrademarksandTheJavaSeriesisatrademarkofO'Reilly&Associates,Inc.Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarks.Wherethosedesignationsappearinthisbook,andO'Reilly&Associates,Inc.wasawareofatrademarkclaim,thedesignationshavebeenprintedincapsorinitialcaps.Whileeveryprecautionhasbeentakeninthepreparationofthisbook,thepublisherassumesnoresponsibilityforerrorsoromissions,orfordamagesresultingfromtheuseoftheinformationcontainedherein.Thisbookisprintedonacid-freepaperwith85%recycledcontent,15%post-consumerwaste.O'Reilly&Associatesiscommittedtousingpaperwiththehighestrecycledcontentavailableconsistentwithhighquality.ISBN.1-56592-139-9[12/98]Pagev TableofContentsPrefacexvI:TheBasics11:WhatIsC++?33ABriefHistoryofC++3C++Organization4HowtoLearnC++62:TheBasicsofProgramWriting9ProgramsfromConceptiontoExecution12CreatingaRealProgram13CreatingaProgramUsingaCommand-LineCompiler13CreatingaProgramUsinganIntegratedDevelopmentEnvironment16GettingHelpinUNIX32GettingHelpinanIntegratedDevelopmentEnvironment33ProgrammingExercises333:Style35Comments36C++Code441NamingStyle42CodingReligion43IndentationandCodeFormat43PageviClarity44 44Simplicity45ConsistencyandOrganization46FurtherReading46Summary464:BasicDeclarationsandExpressions49TheElementsofaProgram49BasicProgramStructure50SimpleExpressions51ThecoutOutputClass53VariablesandStorage53VariableDeclarations54Integers55AssignmentStatements56FloatingPointNumbers57FloatingPointVersusIntegerDivide58Characters59ProgrammingExercises60AnswersChapterQuestions615:Arrays,Qualifiers,andReadingNumbers63Arrays63Strings64ReadingData67InitializingVariables69MultidimensionalArrays70TypesofIntegers72TypesofFloats74 74ConstantandReferenceDeclarations74Qualifiers76HexadecimalandOctalConstants78OperatorsforPerformingShortcuts78SideEffects79ProgrammingExercises82AnswerstoChapterQuestions82Pagevii6:DecisionandControlStatements85ifStatement85elseStatement87HowNottoUsestrcmp88LoopingStatements88whileStatement88BreakStatement91continueStatement92TheAssignmentAnywhereSideEffect92ProgrammingExercises94AnswerstoChapterQuestions957.TheProgrammingProcess97SettingUp99TheSpecification100CodeDesign101ThePrototype102TheMakefile103 103Testing105Debugging106Maintenance108Revisions108ElectronicArchaeology109MarkUptheProgram109UsetheDebugger110UsetheTextEditorasaBrowser110AddComments110ProgrammingExercises113II:SimpleProgramming1158:MoreControlStatements117forStatement117switchStatement120switch,break,andcontinue125ProgrammingExercises127AnswerstoChapterQuestions128Pagevii9:VariableScopeandFunctions129ScopeandStorageClass129Functions133SummaryofParameterTypes146StructuredProgrammingBasics146Recursion148 148ProgrammingExercises149AnswerstoChapterQuestions14910.TheC++Preprocessor151#defineStatement151ConditionalCompilation157#includeFiles159ParameterizedMacros160AdvancedFeatures162Summary163ProgrammingExercises163AnswerstoChapterQuestions16411:BitOperations167BitOperators168TheANDOperator(&)168BitwiseOR(|)171TheBitwiseExclusiveOR(^)171TheOnesComplementOperator(NOT)(-)171TheLeftandRightShiftOperators(<<,>>)172Setting,Clearing,andTestingBits173BitmappedGraphics176ProgrammingExercises181AnswerstoChapterQuestions182III:AdvancedTypesandClasses18312:AdvancedTypes185Structures185 185Unions188typedef190PageixenumType191BitFieldsorPackedStructures193ArraysofStructures195ProgrammingExercises19613:SimpleClasses197Stacks197ImprovedStack201UsingaClass203IntroductiontoConstructorsandDestructors205AutomaticallyGeneratedMemberFunctions210Shortcuts211Style212ProgrammingExercises21414:MoreonClasses217Friends217ConstantFunctions219ConstantMembers220StaticMemberVariables222StaticMemberFunctions223TheMeaningofstatic224ProgrammingExercises225 22515:SimplePointers227ConstantPointers232PointersandPrinting233PointersandArrays233SplittingStrings237PointersandStructures240Command-LineArguments241ProgrammingExercises245AnswerstoChapterQuestions245PagexIV:AdvancedProgrammingConcepts24916:FileInput/Output251C++FileI/O252ConversionRoutines256BinaryandASCIIFiles260TheEnd-of-LinePuzzle261BinaryI/O262BufferingProblems263UnbufferedI/O264DesigningFileFormats268C-StyleI/ORoutines270C-StyleConversionRoutines273C-StyleBinaryI/O276ProgrammingExercises278 278AnswerstoChapterQuestions27817:DebuggingandOptimization281Debugging281SerialDebugging289DivideandConquer290Debug-OnlyCode290DebugCommand-LineSwitch290GoingThroughtheOutput292InteractiveDebuggers292DebuggingaBinarySearch296RuntimeErrors307TheConfessionalMethodofDebugging309Optimization309ThePowerofPowersof2311HowtoOptimize314CaseStudy:InlineFunctionsVersusNormalFunctions316CaseStudy:OptimizingaColor-RenderingAlgorithm316ProgrammingExercises317AnswerstoChapterQuestions317Pagexi18:OperatorOverloading319OperatorFunctions322OperatorMemberFunctions330FullDefinitionoftheComplexClass332 332ProgrammingExercises341AnswerstoChapterQuestions34219:FloatingPoint343Floating-PointFormat343FloatingAddition/Subtraction344Multiplication345Division346OverflowandUnderflow346RoundoffError347Accuracy347MinimizingRoundoffError348DeterminingAccuracy348PrecisionandSpeed350PowerSeries351ProgrammingExercises35220:AdvancedPointers355Pointers,Structures,andClasses355deleteOperator358LinkedList359OrderedLinkedLists362Double-linkedList365Trees368PrintingaTree373TheRestoftheProgram373DataStructuresforaChessProgram377ProgrammingExercises378 378AnswerstoChapterQuestions37921:AdvancedClasses381DerivedClasses381VirtualFunctions387PagexiiVirtualClasses393FunctionHidinginDerivedClasses395ConstructorsandDestructorsinDerivedClasses396Summary398ProgrammingExercises399AnswerstoChapterQuestions399V:OtherLanguageFeatures40122:Exceptions403StackExceptions405RuntimeLibraryExceptions410ProgrammingExercises41023:ModularProgramming413Modules413PublicandPrivate414TheexternModifier414Headers416TheBodyoftheModule418AProgramtoUseInfiniteArrays418TheMakefileforMultipleFiles420UsingtheInfiniteArray424 424DividingaTaskintoModules429ModuleDivisionExample:TextEditor430CompilerConstruction431Spreadsheet432ModuleDesignGuidelines433ProgrammingExercises43424:Templates435WhatIsaTemplate?435Templates:TheHardWay435FunctionSpecialization439ClassTemplates440ClassSpecialization442ImplementationDifficulties442PagexiiiSummary445ProgrammingExercises44525:PortabilityProblems447Modularity447WordSize448Byte-OrderProblem448AlignmentProblem449NULL-PointerProblem450FilenameProblems451FileTypes452 452Summary452AnswerstoChapterQuestions45326:PuttingItAllTogether455Requirements455CodeDesign457Coding459FunctionalDescription459Testing463Revisions464AFinalWarning464ProgramFiles464ProgrammingExercises48327:FromCtoC++485Overview485K&R-StyleFunctions485struct486mallocandfree486TurningStructuresintoClasses488ssetjmpandlongjmp489Summary491ProgrammingExercise491Pagexiv28.C++'sDustierCorners493do/while493 493goto493The?:Construct495TheCommaOperator495Overloadingthe()Operator495PointerstoMembers496VampireFeatures497AnswerstoChapterQuestions49829:ProgrammingAdages499General499Design500Declarations500switchStatement500Preprocessor500Style501Compiling501TheTenCommandmentsforC++Programmers501FinalNote502AnswerstoChapterQuestions503VI:Appendixes505A:ASCIITable507B:Ranges511C:OperatorPrecedenceRules513D:ComputingsineUsingaPowerSeries515Glossary521Index543 PagexvPrefaceThisbookisdevotedtopracticalC++programming.Itteachesyounotonlythemechanicsofthelanguage,butalsostyleanddebugging.Theentirelifecycleofaprogramisdiscussed,includingconception,design,writing,debugging,release,documentation,maintenance,andrevision.Styleisemphasized.Creatingagoodprograminvolvesmorethanjusttypingcode.Itisanartinwhichwritingandprogrammingskillsblendtoformamasterpiece.Awell-writtenprogramnotonlyfunctionscorrectly,butalsoissimpleandeasytounderstand.Commentsallowprogrammerstoincludedescriptivetextintheirprograms.Clearlywritten,well-commentedprogramsarehighlyprized.Aprogramshouldbeassimpleaspossible.Avoidtheuseofclevertricks.Clevernessandcomplexitycankillprograms.Thisbookstressessimple,practicalrules.Forexample,the15operator-precedencerulesinC++canbesimplifiedto2:1.Multiplyanddividebeforeyouaddandsubtract.2.Putparenthesesaroundeverythingelse.Considertwoprograms.Onewaswrittenbyacleverprogrammer,usingallthetricks.Theprogramcontainsnocomments,butitworks.Theotherisnicelycommentedandwellstructured,butdoesn'twork.Whichprogramismoreuseful?Inthelongrun,the''broken"oneismoreusefulbecauseitcanbefixedandmaintainedeasily.Althoughthecleveroneworksnow,soonerorlateritwillhavetobemodified.Thehardestworkyouwilleverhavetodoismodifyingacleverlywrittenprogram.PagexviScopeofThisHandbookThishandbookiswrittenforpeoplewithnopreviousprogrammingexperience,forprogrammerswhoknowCandwanttoupgradetheirskillstoC++,andforthosewhoalreadyknowC++andwanttoimprovetheirprogrammingstyleandreliability.Youshouldhaveaccesstoacomputerandknowhowtousethebasicfunctionssuchasthetexteditorandfilesystem.Computerlanguagesarebestlearnedbywritinganddebuggingprograms.Sweatingoverabrokenprogramattwoo'clockinthemorningonlytofindthatyoutyped=whereyoushouldhavetyped==isaveryeffectiveteachingtool.Manyprogrammingexamplesareusedthroughoutthisbook.Mostofthemcontaindeliberateerrors.Youareencouragedtoentertheexamplesintoyourcomputerandthenrunanddebugthem.Thisprocessintroducesyoutocommonerrorsusingshortprogramssoyouwillknowhowtospotandcorrectsucherrorsin yourownlargerprograms.(Instructionsforobtainingcopiesoftheprogramspresentedinthisbookarelocatedattheendofthischapter.)SeveraldialectsofC++arepresented:·A"generic"UNIXcompilerthatshouldworkonmostUNIXsystems·TheGNUC++compiler,namedg++(availableformostUNIXsystems*)·Borland'sTurboC++compilerforMS-DOS·BorlandC++forMS-DOS/Windows·Microsoft'sVisualC++forMS-DOS/WindowsAsfarasstandardC++isconcernedthereareonlyminordifferencesamongthevariouscompilers.Thisbookclearlyindicateswherecompilerdifferencescanaffecttheprogrammer.Specificinstructionsaregivenforproducingandrunningprogramsusingeachofthesecompilers.Thebookalsogivesexamplesofusingtheprogrammingutilitymakeforautomatedprogramproduction.HowThisBookIsOrganizedYoumustcrawlbeforeyouwalk.InPartI:TheBasicsyoulearnhowtocrawl.Thesechaptersteachyouenoughtowriteverysimpleprograms.Youstartwiththemechanicsofprogrammingandprogrammingstyle.Next,youlearnhowtousevariablesandverysimpledecisionandcontrolstatements.*TheGNUg++compilercanbeobtainedbyanonymousFTPfromprep.almitedu,oryoucancontacttheFreeSoftwareFoundation,Inc,at675MassachusettsAvenue,Cambridge,MA02139,(617)876-3296.PagexviiAtthispointyouwillhavelearnedenoughtocreateverysimpleprograms;therefore,inChapter7,TheProgrammingProcess,youembarkonacompletetouroftheprogrammingprocessthatshowsyouhowrealprogramsarecreated.Chapter1,WhatIsC++?,givesyouanovervieinsthebasicprogrammingprocessandgivesyouenoughinformationtowriteaverysimpleprogram.wofC++,describesitshistoryanduses,andexplainshowthelanguageisorganized.Chapter2,TheBasicsofProgramWriting,explaChapter3,Style,discussesprogrammingstyle.HoChapter4,BasicDeclarationsandExpressions,intwtocommentaprogramiscovered,aswellashowtowriteclearandsimplecode.roducessimpleC++statements.Basicvariablesandtheassignmentstatementarecoveredindetailalongwiththearithmeticoperators:+,-,*,/,and%.Chapter5,Arrays,Qualifiers,andReadingNumbers,coversarraysandmorecomplex variables.Theshorthandoperators++,--,*=,=,+=,-=,and%=aredescribed.Chapter6,DecisionandControlStatements,explainssimpledecisionstatementsincludingif,elseandfor.Theproblemof==versus=isdiscussed.Chapter7,TheProgrammingProcess,takesyouthroughthestepsrequiredforcreatingasimpleprogram,fromspecificationthroughrelease.Structuredprogramming,fastprototyping,anddebuggingarediscussed.PartII:SimpleProgramming,describesalltheothersimplestatementsandoperatorsthatareusedinprogramming.Youalsolearnhowtoorganizethesestatementsintosimplefunctions.Chapter8,MoreControlStatements,describesadditionalcontrolstatements.Includedarewhile,break,andcontinue.Theswitchstatementisdiscussedindetail.Chapter9,VariableScopeandFunctions,introduceslocalvariables,functions,andparameters.Chapter10,TheC++Preprocessor,describestheC++preprocessor,whichgivesyougreatflexibilityincreatingcode.Italsoprovidesatremendousnumberofwaysforyoutoscrewup.Simplerulesthathelpkeepthepreprocessorfrombecomingaproblemaredescribed.Chapter11,BitOperations,discussesthelogicalC++operatorsthatworkonbits.InPartIII:AdvancedTypesandClasses,youlearnhowbasicdeclarationsandstatementscanbeusedintheconstructionofadvancedtypessuchasstructures,unions,andclasses.Youalsolearnabouttheconceptofpointers.PagexviiiChapter12,AdvancedTypes,explainsstructuresandotheradvancedtypes.Thesizeofoperatorandtheenumtypeareincluded.Chapter13,SimpleClasses,introducestheconceptofaclass.ThisisoneofthemorepowerfulfeaturesofC++.Classesallowyoutogroupdataandtheoperationsthatcanbeperformedonthatdataintooneobject.Chapter14,MoreonClasses,describesadditionaloperationsthatcanbeperformedwithclasses.Chapter15,SimplePointers,introducesC++pointervariablesandshowssomeoftheiruses.AdvancedprogrammingtechniquesareexploredinPartIV:AdvancedProgrammingConcepts.Inthissection,youexploreanumberofC++featuresthatletyoucreatecomplex,yeteasy-to-useobjectsorclasses.Chapter16,FileInput/Output,describesbothbufferedandunbufferedinput/output(I/O).ASCIIandbinaryfilesarediscussedandyouareshownhowtoconstructasimplefile.OldC-styleI/Ooperationsarealsoincluded.Chapter17,DebuggingandOptimization,describeshowtodebugaprogram,aswellashowtouseaninteractivedebugger.Youareshownnotonlyhowtodebugaprogram,butalsohowtowriteaprogramsothatitiseasytodebug.Thischapteralsodescribesmany optimizationtechniquestomakeyourprogramsrunfasterandmoreefficiently.Chapter18,OperatorOverloading,explainsthatC++allowsyoutoextendthelanguagebydefiningadditionalmeaningsforthelanguage'soperators.Inthischapter,youcreateacomplextypeandtheoperatorsthatworkonit.Chapter19.FloatingPoint,usesasimpledecimalfloating-pointformattointroducetheproblemsinherentinusingfloatingpoints,suchasroundofferrors,precisionloss,overflow,andunderflow.Chapter20,AdvancedPointers,describesadvanceduseofpointerstoconstructdynamicstructuressuchaslinkedlistsandtrees.Chapter21,AdvancedClasses,showshowtobuildcomplex,derivedclassesoutofsimple,baseones.FinallyanumberofmiscellaneousfeaturesaredescribedinV:OtherLanguageFeatures.Chapter22,Exceptions,explainshowtohandleunexpectedconditionswithinaprogram.PagexixChapter23,ModularProgramming,showshowtosplitaprogramintoseveralfilesandusemodularprogrammingtechniques.Themakeutilityisexplainedinmoredetail.Chapter24,Templates,allowsyoutodefineagenericfunctionorclassthatgeneratesafamilyoffunctions.Chapter25,PortabilityProblems,describestheproblemsthatcanoccurwhenportingaprogram(movingaprogramfromonemachinetoanother).Chapter26,PuttingItAllTogether,detailsthestepsnecessarytotakeacomplexprogramfromconceptiontocompletion.Informationhidingandmodularprogrammingtechniques,aswellasobject-orientedprogramming,arestressed.Chapter27,FromCtoC++,describeshowtoturnCcodeintoC++code,andaddressesmanyofthetrapslurkinginCcodethatbitetheC++programmer.Chapter28,C++'sDustierCorners,describesthedo/whilestatement,thecommaoperator,andthe?:operators.Chapter29,ProgrammingAdages,listsprogrammingadagesthatwillhelpyouconstructgoodC++programs.AppendixA,ASCIITable,containsalistofcharactercodesandtheirvalues.AppendixB,Ranges,liststhenumericrangesofsomeC++variabletypes.AppendixC,OperatorPrecedenceRules,liststherulesthatdeterminetheorderinwhichoperatorsareevaluated.AppendixD,ComputingsineUsingaPowerSeries,containsaprogramthatshowshowthecomputercancomputethevalueofthesinefunction. HowtoReadThisBookIfYouAlreadyKnowCC++isbuiltontheClanguage.IfyouknowC,youwillfindmuchofthematerialpresentedinChapters2through12familiar.C++doesintroduceanumberofnewfeatures,including:·AnentirelynewI/Osystem.(ThebasicsaredescribedinChapter4,BasicDeclarationsandExpressions.ThenewfilesystemisdiscussedindetailinChapter16,FileInput/Output.)·Constantandreferencevariables.(DescribedinChapter5,Arrays,Qualifiers,andReadingNumbers.)Pagexx·Functionoverloading,inlinefunctions,referenceparameters,anddefaultparameters.(ReadChapter9,VariableScopeandFunctions.)StartingwithChapter13,SimpleClasses,youwillbegintolearnentirelynewconcepts.ClassesareuniquetoC++andareoneofthemorepowerfulfeaturesofthelanguage.FontConventionsThefollowingconventionsareusedinthisbook:Italicisusedfordirectoriesandtoemphasizenewtermsandconceptswhentheyareintroduced.Italicisalsousedtohighlightcommentsinexamples.BoldisusedforCkeywords.ConstantWidthisusedforprogramsandtheelementsofaprogramandinexamplestoshowthecontentsoffilesortheoutputfromcommands.Areferenceintexttoawordoritemusedinanexampleorcodefragmentisalsoshowninconstantwidthfont.ConstantBoldisusedinexamplestoshowcommandsorothertextthatshouldbetypedliterallybytheuser.(Forexample,rmfoomeanstotype"rmfoo"exactlyasitappearsinthetextortheexample.)ConstantItalicisusedinexamplestoshowvariablesforwhichacontext-specificsubstitutionshouldbemade.(Thevariablefilename,forexample,wouldbereplacedbysomeactualfilename.)Quotesareusedtoidentifysystemmessagesorcodefragmentsinexplanatorytext.% istheUNIXCshellprompt.$istheUNIXBourneshellorKornshellprompt.#istheUNIXsuperuserprompt(eitherBourneorCshell).Weusuallyusethisforexamplesthatshouldbeexecutedonlybyroot.Pagexxi[]surroundoptionalvaluesinadescriptionofprogramsyntax.(Thebracketsthemselvesshouldneverbytyped.)...standsfortext(usuallycomputeroutput)that'sbeenomittedforclarityortosavespace.ThenotationCTRL-Xor^Xindicatesuseofcontrolcharacters.Itmeansholddownthe"control"keywhiletypingthecharacter"x".Wedenoteotherkeyssimilarly(e.g.,RETURNindicatesacarriagereturn).AllexamplesofcommandlinesarefollowedbyaRETURNunlessotherwiseindicated.ObtainingSourceCodeYoucanobtainthesourcecodefortheprogramspresentedinthisbookfromO'Reilly&AssociatesthroughtheirInternetserver.Theexampleprogramsinthisbookareavailableelectronicallyinanumberofways:byFTP,Ftpmail,BITFTP,andUUCP.Thecheapest,fastest,andeasiestwaysarelistedfirst.Ifyoureadfromthetopdown,thefirstonethatworksforyouisprobablythebest.UseFTPifyouaredirectlyontheInternet.UseFtpmailifyouarenotontheInternet,butcansendandreceiveelectronicmailtoInternetsites(thisincludesCompuServeusers).UseBITFTPifyousendelectronicmailviaBITNET.UseUUCPifnoneoftheaboveworks.FTPTouseFTP,youneedamachinewithdirectaccesstotheInternet.Asamplesessionisshown,withwhatyoushouldtypeinboldface.%ftpftp.uu.netConnectedtoftp.uu.net.220FTPserver(Version6.21TueMar1022:09:55EST1992)ready.Name(ftp.uu.net:joe):anonymous331Guestloginok,senddomainstylee-mailaddressaspassword.Password:joe@ora.com(useyourusernameandhosthere)230Guestloginok,accessrestrictionsapply.ftp>cd/published/oreilly/nutshell/practcpp250CWDcommandsuccessful.ftp>binary(Veryimportant!Youmustspecifybinarytransferforcompressedfiles)200TypesettoI.ftp>getexamples.tar.gz 200PORTcommandsuccessful.150OpeningBINARYmodedataconnectionforexamples.tar.gz.226Transfercomplete.Pagexxiiftp>quit221Goodbye.%Thefileisacompressedtararchive;extractthefilesfromthearchivebytyping:%gzcatexamples.tar.gz|tarxvf-SystemVsystemsrequirethefollowingtarcommandinstead:%gzcatexamples.tar.gz|tarxof-Ifgzcatisnotavailableonyoursystem,useseparategunzipandtarorsharcommands.%gunzipexamples.tar.gz%tarxvfexamples.tarFtpmailFtpmailisamailserveravailabletoanyonewhocansendelectronicmailtoandreceiveitfromInternetsites.ThisincludesanycompanyorserviceproviderthatallowsemailconnectionstotheInternet.Here'showyoudoit.Yousendmailtoftpmail@online.ora.com.Inthemessagebody,givetheFTPcommandsyouwanttorun.TheserverwillrunanonymousFTPforyouandmailthefilesbacktoyou.Togetacompletehelpfile,sendamessagewithnosubjectandthesingleword"help"inthebody.Thefollowingisasamplemailsessionthatshouldgetyoutheexamples.Thiscommandsendsyoualistingofthefilesintheselecteddirectoryandtherequestedexamplefiles.Thelistingisusefulifthere'salaterversionoftheexamplesyou'reinterestedin.%mailftpmaileonline.ora.comSubject:reply-tojanetvgxyz.com(Whereyouwantfilesmailed)opencd/published/oreilly/nutshell/practcppmodebinaryuuencodegetexamples.tar.gzquit.Asignatureattheendofthemessageisacceptableaslongasitappearsafter"quit."BITFTPBITFTPisamailserverforBITNETusers.Yousenditelectronicmailmessagesrequestingfiles,anditsendsyoubackthefilesbyelectronicmail.BITFTPcurrentlyPagexxiii servesonlyuserswhosenditmailfromnodesthataredirectlyonBITNET,EARN,orNetNorth.BITFTPisapublicserviceofPrincetonUniversity.Here'showitworks.TouseBITFTP,sendmailcontainingyourftpcommandstoBITFTP@PUCC.Foracompletehelpfile,sendHELPasthemessagebody.ThefollowingisthemessagebodyyousendtoBITFTP:FTPftp.uu.netNETDATAUSERanonymousPASSmyname@podunk.eduPutyourInternetemailaddresshere(notyourBITNETaddress)CD/published/oreilly/nutshell/practcppDIRBINARYGETexamples.tar.gzQUITOnceyou'vegotthedesiredfile,followthedirectionsunderFTPtoextractthefilesfromthearchive.SinceyouareprobablynotonaUNIXsystem,youmayneedtogetversionsofuudecode,uncompress,atob,andtarforyoursystem.VMS,DOS,andMacversionsareavailable.UUCPUUCPisstandardonvirtuallyallUNIXsystemsandisavailableforIBM-compatiblePCsandAppleMacintoshes.TheexamplesareavailablebyUUCPviamodemfromUUNET;UUNET'Sconnect-timechargesapply.YoucangettheexamplesfromUUNETwhetheryouhaveanaccountthereornot.IfyouoryourcompanyhasanaccountwithUUNET,youhaveasystemsomewherewithadirectUUCPconnectiontoUUNET.Findthatsystem,andtype:uucpuunet!~/published/oreilly/nutshell/practcpp/examples.tar.gzyourhost!~/yourname/ThebackslashescanbeomittedifyouusetheBourneshell(sh)insteadofcsh.Thefileshouldappearsometimelater(uptoadayormore)inthedirectory/usr/spool/uucppublicyourname.Ifyoudon'thaveanaccount,butwouldlikeonesothatyoucangetelectronicmail,contactUUNETat703-204-8000.It'sagoodideatogetthefile/published/oreilly/ls-lR.Zasashorttestfilecontainingthefilenamesandsizesofallthefilesavailable.Onceyou'vegotthedesiredfile,followthedirectionsunderFTPtoextractthefilesfromthearchive.PagexxivCommentsandQuestionsPleaseaddresscommentsandquestionsconcerningthisbooktothepublisher:O'Reilly&Associates,Inc. 101MorrisStreetSebastopol,CA954721-800-998-9938(intheU.S.orCanada)1-707-829-0515(internationalorlocal)1-707-829-0104(FAX)AcknowledgmentsThankstoPegKovarforherproofreadingandeditinghelp.SpecialthankstoDaleDoughertyforrippingapartmyfirstbookandforcingmetoputittogethercorrectly.IgreatlyappreciatethehardworkputinbyPhilStraiteandGregorySatir.Iespeciallythankallthosepeoplewhoreviewedandeditedmybook.MythanksalsogototheproductiongroupatO'Reilly&Associates—NicoleGipson,projectmanagerandproductioneditor;JohnFiles,JulietteMuellner,andJaneEllln,productionassistants;andMikeSierra,bookdesignimplementor.Finally,specialthanksgotoallthehard-workingprogrammersouttherewhosecodehastaughtmesomuch.Page1ITheBasicsPage31WhatIsC++?InThisChapter:·ABriefHistotyofC++·C++Organization·HowtoLearnC++Profanityistheonelanguagethatallprogrammersunderstand.—AnonymousTheabilitytoorganizeandprocessinformationisthekeytosuccessinthemodernage.Computersaredesignedtohandleandprocesslargeamountsofinformationquicklyandefficiently.However,theycan'tdoanythinguntilsomeonetellsthemwhattodo.That'swhereC++comesin.C++isahigh-levelprogramminglanguagethatallowsasoftwareengineertoefficientlycommunicatewithacomputer. C++isahighlyflexibleandadaptablelanguage.Sinceitscreationin1980,ithasbeenusedforawidevarietyofprogramsincludingfirmwareformicro-controllers,operatingsystems,applications,andgraphicsprogramming.C++isquicklybecomingtheprogramminglanguageofchoice.Thereisatremendousdemandforpeoplewhocantellcomputerswhattodo,andC++letsyoudosoquicklyandefficiently.ABriefHistoryofC++In1970twoprogrammers,BrianKernighanandDennisRitchie,createdanewlanguagecalledC.(ThenamecameaboutbecauseCwasprecededbytheoldprogramminglanguagetheywereusingcalledB.)Cwasdesignedwithonegoalinmind:writingoperatingsystems.Thelanguagewasextremelysimpleandflexibleandsoonwasusedformanydifferenttypesofprograms.Itquicklybecameoneofthemostpopularprogramminglanguagesintheworld.Page4Chadonemajorproblem,however.Itwasaprocedure-orientedlanguage.ThismeantthatindesigningatypicalCprogram,theprogrammerwouldstartbydescribingthedataandthenwriteprocedurestomanipulatethatdata.Programmerseventuallydiscoveredthatitmadeaprogramclearerandeasiertounderstandiftheywereabletotakeabunchofdataandgroupittogetherwiththeoperationsthatworkedonthatdata.Suchagroupingiscalledanobjectorclass.Designingprogramsbydesigningclassesisknownasobject-orienteddesign(OOD).In1980BjarneStroustrupstartedworkingonanewlanguage,called''CwithClasses."ThislanguageimprovedonCbyaddinganumberofnewfeatures,themostimportantofwhichwasclasses.Thislanguagewasimproved,augmented,andfinallybecameC++.C++owesitssuccesstothefactthatitallowstheprogrammertoorganizeandprocessinformationmoreeffectivelythanmostotherlanguages.Also,itbuildsontheworkalreadydonewiththeClanguage.Infact,mostCprogramscanbetransformedintoC++programswithlittletrouble.Theseprogramsusuallydon'tuseallthenewfeaturesofC++,buttheydowork.Inthisway,C++allowsprogrammerstobuildonanexistingbaseofCcode.C++OrganizationC++isdesignedasabridgebetweentheprogrammerandtherawcomputer.Theideaistolettheprogrammerorganizeaprograminawaythatheorshecaneasilyunderstand.Thecompilerthentranslatesthelanguageintosomethingthemachinecanuse.Computerprogramsconsistoftwomainparts:dataandinstructions.Thecomputerimposeslittleornoorganizationonthesetwoparts.Afterall,computersaredesignedtobeasgeneralaspossible.Theideaisfortheprogrammertoimposehisorherownorganizationonthecomputerandnottheotherwayaround.Thedatainacomputerisstoredasaseriesofbytes.C++organizesthosebytesintousefuldata.Datadeclarationsareusedbytheprogrammertodescribetheinformationheorsheisworkingwith.Forexample:inttotal;//Totalnumberaccounts tellsC++thatyouwanttouseasectionofthecomputer'smemorytostoreanintegernamedtotal.Youcanletthecompilerdecidewhatparticularbytesofmemorytouse;that'saminorbookkeepingdetailyoudon'tneedtoworryabout.Page5Thevariabletotalisasimplevariable.Itcanholdonlyoneintegeranddescribeonlyonetotal.Aseriesofintegerscanbeorganizedintoanarray.Again,C++willhandlethedetails,imposingthatorganizationonthecomputer'smemory.intbalance[100];//Balance(incents)forall100accountsFinally,therearemorecomplexdatatypes.Forexample,arectanglemighthaveawidth,aheight,acolor,andafillpattern.C++letsyouorganizethesefourattributesintoonegroupcalledastructure.structrectangle{intwidth;//Widthofrectangleinpixelsintheight;//Heightofrectangleinpixelscolor_typecolor;//Coloroftherectanglefill_typefill;//Fillpattern};However,dataisonlyonepartofaprogram.Youalsoneedinstructions.Asfarasthecomputerisconcerneditknowsnothingaboutthelayoutoftheinstructions.Itknowsonlywhatit'sdoingforthecurrentinstructionandwheretogetthenextinstruction.C++isahigh-levellanguage.Itletsyouwriteahigh-levelstatementsuchas:area=(base*height)/2.0;//ComputeareaoftriangleThecompilertranslatesthisstatementintoaseriesofcrypticmachineinstructions.Thissortofstatementiscalledanassignmentstatement.Itisusedtocomputeandstorethevalueofanarithmeticexpression.Youcanalsousecontrolstatementstocontroltheorderofprocessing.Statementssuchastheifandswitchstatementsenablethecomputertomakesimpledecisions.Statementscanberepeatedbyusingloopingstatementssuchaswhileandfor.Groupsofstatementscanbewrappedtoformfunctions.Thusyouonlyneedtowriteageneral-purposefunctiontodrawarectangleonceandthenyoucanreusethatfunctionwheneveryouwanttodrawanewrectangle.C++providesarichsetofstandardfunctionsthatperformcommonfunctionssuchassearching,sorting,input,andoutput.Asetofrelatedfunctionscanbegroupedtogethertoformamodule,andmodulesarelinkedtoformprograms.OneofthemajorgoalsoftheC++languageistoorganizeinstructionsintoreusablecomponents.Afterall,youcanwriteprogramsmuchfasterifyou"borrow"mostofyourcodefromsomewhereelse.Groupsofreusablemodulescanbecombinedintoalibrary.Forexample,ifyouneedasortroutine,youcanusethestandardfunctionqsortfromthelibraryandlinkitintoyourprogram. Page6Acomputerdividestheworldintodataandinstructions.Foralongtime,highlevellanguagessuchasCkeptthatdividinglineinplace.InCyoucandefinedataorwriteinstructions,butyoucan'tcombinethetwo.OneofC++'smajorinnovationsistheideaofcombiningdataandinstructionstogetherinaconstructcalledaclassorobject.Object-orientedprogrammingallowsyoutogroupdatawiththeoperationsthatcanbeperformedonthatdata.ThisconceptistakenonestepfurtherinC++byallowingyoutoderivenewclassesfromexistingones.Thislastfeatureisextremelypowerful.Itallowsyoutobuildcomplexclassesontopofsmaller,simplerones.Italsoallowsyoutodefineabasic,abstractclassandthenderivespecificclassesfromit.Forexample,anabstractclassofshapemightbeusedtodefinetheshapesrectangle,triangle,andcircle.Organizationisthekeytowritinggoodprograms.Inthisbook,youknowthatthetableofcontentsisinthefrontandtheindexisintheback,becausethat'sthewaybooksareorganized.Organizationmakesthisbookeasiertouse.TheC++languageletsyouorganizeyourprogramsusingasimpleyetpowerfulsyntax.ThisbookgoesbeyondtheC++syntaxandteachesyoustylerulesthatenableyoutocreatehighlyreadableandreliableprograms.Bycombiningapowerfulsyntaxwithagoodprogrammingstyleyoucancreatepowerfulprogramsthatperformcomplexandwonderfuloperations.HowtoLearnC++Theonlywaytolearnhowtoprogramistowriteprograms.You'lllearnalotmorebywritinganddebuggingprogramsthanyoueverwillbyreadingthisbook.Thisbookcontainsmanyprogrammingexercises,andyoushouldtrytodoasmanyofthemaspossible.Whendoingtheexerciseskeepgoodprogrammingstyleinmind.Alwayscommentyourprograms,evenifyou'redoingtheexercisesonlyforyourself.Commentinghelpsyouorganizeyourthoughts,andcommentingyourownprogramsisgoodpracticeforwhenyougointothe"realworld."Don'tletyourselfbeseducedbytheideathat,"I'monlywritingtheseprogramsformyself,soIdon'tneedtocommentthem."Firstofall,codethatlooksobvioustoyouwhenyouwriteitcanoftenbeconfusingandcrypticwhenyourevisititaweeklater.Writingcommentsalsohelpsyouorganizeyourideas.(IfyoucanwriteoutanideainEnglish,youarehalfwaytowritingitinC++.)Finally,programstendtobearoundfarlongerthanexpected.IoncewroteaprogramthatwasdesignedtoworkonlyonthecomputeratCaltech.Theprogramwashighlysystemdependent.AsIwastheonlyonewhowouldeverPage7usetheprogram,theprogramwouldprintthefollowingmessageifIgotthecommandlinewrong:?LSTUITUserisatwit AfewyearslaterIwasastudentatSyracuseUniversity.ThesecretaryattheSchoolofComputerScienceneededaprogramthatwassimilartomyCaltechlistingprogram,soIadaptedmyprogramforheruse.Unfortunately,Ihadforgottenaboutmyfunnylittleerrormessage.ImaginehowhorrifiedIwaswhenIcameintotheComputerScienceofficeandwasaccostedbythechiefsecretary.Thisladyhadsomuchpowershecouldmakethedeancringe.Shelookedatmeandsaid,"Userisatwit,huh?"Luckilyshehadasenseofhumor,orImightnotbeheretoday.Sprinkledthroughoutthisbookare"broken"programs.Spendthetimetofigureoutwhytheydon'twork.Oftentheproblemisverysubtle,suchasamisplacedsemicolonorusing=insteadof==.Theseprogramsletyoulearnhowtospotmistakesinasmallprogram.Thatwaywhenyoumakesimilarmistakesinabigprogram,andyouwillmakemistakes,youwillbetrainedtospotthem.Page92TheBasicsofProgramWritingInThisChapter:·ProgramsfromConceptiontoExecution·CreatingaRealProgram·CreatingaProgramUsingaCommand-LineCompiler·CreatingaProgramUsinganIntegratedDevelopmentEnvironment·GettingHelp·ProgrammingExercisesThefirstandmostimportantthingofall,atleastforwriterstoday,istostriplanguageclean,tolayitbaredowntothebone—ErnestHemingwayComputersareverypowerfultoolsthatcanstore,organize,andprocessatremendousamountofinformation.However,theycan'tdoanythinguntilsomeonegivesthemdetailedinstructions.Communicatingwithcomputersisnoteasy.Theyrequireinstructionsthatareexactand detailed.Wouldn'tlifebeeasierifwecouldwriteprogramsinEnglish?Thenwecouldtellthecomputer,"Addupallmychecksanddeposits,andthentellmethetotal,"andthemachinewouldbalanceourcheckbooks.ButEnglishisalousylanguagewhenyoumustwriteexactinstructions.Thelanguageisfullofambiguityandimprecision.GraceHopper,thegrandoldladyofcomputing,oncecommentedontheinstructionsshefoundonabottleofshampoo:WashRinseRepeatShetriedtofollowthedirections,butsheranoutofshampoo.(Wash-rinse-repeat.Wash-rinse-repeat.Wash-rinse-repeat....)Ofcourse,wecantrytowriteinpreciseEnglish.We'dhavetobecarefulandmakesuretospelleverythingoutandbesuretoincludeinstructionsforeverycontingency.Ifweworkedreallyhard,wecouldwritepreciseEnglishinstructions,right?Page10Asitturnsout,thereisagroupofpeoplewhospendtheirtimetryingtowritepreciseEnglish.They'recalledthegovernment,andthedocumentstheywritearecalledgovernmentregulations.Unfortunately,intheirefforttomaketheregulationsprecise,thegovernmentalsohasmadethedocumentsalmostunreadable.Ifyou'veeverreadtheinstructionbookthatcomeswithyourtaxforms,youknowwhatpreciseEnglishcanbelike.Still,evenwithalltheextraverbiagethegovernmentputsin,problemscanoccur.AfewyearsagoCaliforniapassedalawrequiringallmotorcycleriderstowearahelmet.Shortlyafterthislawwentintoeffectacopstoppedaguyfornotwearingahelmet.Themansuggestedthepoliceofficertakeacloserlookatthelaw.Thelawhadtworequirements:1)thatmotorcycleridershaveanapprovedcrashhelmetand2)thatitbefirmlystrappedon.Thecopcouldn'tgivethemotorcyclistaticketbecausethemandidhaveahelmetfirmlystrappedon—tohisknee.SoEnglish,withallitsproblems,isoutasacomputerlanguage.Now,howdowecommunicatewithacomputer?Thefirstcomputerscostmillionsofdollars,whileatthesametimeagoodprogrammercostabout$15,000ayear.Programmerswereforcedtoprograminalanguagewherealltheinstructionswerereducedtoaseriesofnumbers,calledmachinelanguage.Thislanguagecouldbedirectlyinputintothecomputer.Atypicalmachine-languageprogramlookslike:101011110011011101110110..andsoonforseveralhundredinstructionsWhereasmachines"think"innumbers,peopledon't.Toprogramtheseancientmachines,softwareengineerswouldwriteouttheirprogramsusingasimplelanguagewhereeachwordwouldstandforasingleinstruction.Thiswascalledassemblylanguagebecausethe programmershadtomanuallytranslate,orassemble,eachlineintomachinecode.Atypicalprogrammightlooklike:ProgramTranslationMOVA,4710101111ADDA,B00110111HALT01110110..andsoonforseveralhundredinstructionsThisprocessisillustratedbyFigure2-1.Translationwasadifficult,tedious,exactingtask.Onesoftwareengineerdecidedthiswasaperfectjobforacomputer,sohewroteaprogram,calledanassembler,thatwoulddothejobautomatically.Page11Figure2-1.AssemblingaprogramHeshowedhisnewcreationtohisbossandwasimmediatelychewedout:"Howdareyoueventhinkofusingsuchanexpensivemachineforamere'clerical'task?"Giventhecostofanhourofcomputertimeversusthecostofanhourofprogrammer'stime,thiswasnotanunreasonableattitude.Fortunately,astimepassedthecostofprogrammerswentupandthecostofcomputerswentdown.Soitbecamemorecost-effectivetolettheprogrammerswriteprogramsinassemblylanguageandthenuseaprogramcalledanassemblertotranslatetheprogramsintomachinelanguage.Assemblylanguageorganizedprogramsinawaythatwaseasierfortheprogrammerstounderstand.However,theprogramwasmoredifficultforthemachinetouse.Theprogramhadtobetranslatedbeforethemachinecouldexecuteit.Thiswasthestartofatrend.Programminglanguagesbecamemoreandmoreconvenientforprogrammerstouseandstartedrequiringmoreandmorecomputertimetotranslatethemintosomethingusefulforcomputers.Overtheyearsaseriesofhigh-levellanguageshasbeendevised.Theselanguagesareattemptstoletprogrammerswriteinsomethingthatiseasyforthemtounderstandandthatisalsopreciseandsimpleenoughforcomputerstounderstand.Earlyhigh-levellanguagesweredesignedtohandlespecifictypesofapplications.FORTRANwasdesignedfornumbercrunching;COBOL,forwritingbusinessreports;andPASCAL,forstudentuse.(Manyoftheselanguageshavefaroutgrowntheirinitialuses.ItisrumoredthatNicklausWirthhassaid,"IfIhadknownthatPASCALwasgoingtobesosuccessful,Iwould havebeenmorecarefulinitsdesign.")Lateron,BrianKernighanandDennisRitchiedevelopedCandBjarneStroustrupturneditintoC++.Page12ProgramsfromConceptiontoExecutionC++programsarewritteninahigh-levellanguageusingletters,numbers,andtheothersymbolsyoufindonacomputerkeyboard.Computersactuallyexecuteaverylow-levellanguagecalledmachinecode(aseriesofnumbers).So,beforeaprogramcanbeused,itmustundergoseveraltransformations.Programsstartoutasanideainaprogrammer'shead.Hewritesdownhisthoughtsinafile,calledasourcefileorsourcecode,usingatexteditor.Thisfileistransformedbythecompilerintoanobjectfile.Nextaprogramcalledthelinkertakestheobjectfile,combinesitwithpredefinedroutinesfromastandardlibrary,andproducesanexecutableprogram(asetofmachine-languageinstructions).Inthefollowingsections,you'llseehowthesevariousformsoftheprogramworktogethertoproducethefinalprogram.Figure2-2showsthestepsthatmustbetakentotransformaprogramwritteninahigh-levellanguageintoanexecutableprogram.Figure2-2Transformationofahigh-levellanguageintoaprogramWrappersFortunatelyyoudon'thavetorunthecompiler,assembler,andlinkerindividually.MostC++compilersuse"wrapper"programs,whichdeterminewhichtoolsneedtoberunandthenrunthem. Page13Someprogrammingsystemsgoevenfartherandprovidethedeveloperwithanintegrateddevelopmentenvironment(IDE).TheIDEcontainsaneditor,compiler,linker,projectmanager,debugger,andmoreinoneconvenientpackage.BothBorlandandMicrosoftprovideIDESwiththeircompilers.CreatingaRealProgramBeforeyoucanactuallystartcreatingyourownprogramsyouneedtoknowhowtousethebasicprogrammingtools.Thissectionwilltakeyoustepbystepthroughtheprocessofentering,compiling,andrunningasimpleprogram.Thissectiondescribeshowtousetwodifferenttypesofcompilers.Thefirsttypeisthestandaloneorcommand-linecompiler.Thistypeofcompilerisoperatedinabatchmodefromthecommandline.Inotherwords,youtypeacommandandthecompilerturnsyoursourcecodeintoanexecutableprogram.TheothertypeofcompileriscontainedinanIDE.MostUNIXsystemsusecommand-linecompilers.AfewIDE-typecompilersareavailableforUNIX,buttheyarerare.OntheotherhandalmostallthecompilersusedwithMS-DOSandWindowscontainanintegrateddevelopmentenvironment.Forcommand-linedie-hards,thesecompilersdocontaincommand-linecompilersaswell.CreatingaProgramUsingaCommand-LineCompilerInthissectionyou'llgothroughthestep-by-stepprocessneededtocreateaprogramusingacommand-linecompiler.InstructionisgivenforusingagenericUNIXcompiler,theFreeSoftwareFoundation'sg++compiler,Turbo-C++,BorlandC++,andMicrosoftVisualC++.However,ifyouareusingaBorlandorMicrosoftcompiler,youmightwanttoskipaheadtothesectiononusingtheIDE.Step1:CreateaPlaceforYourProgramItiseasiertomanagethingsifyoucreateaseparatedirectoryforeachprogramyouareworkingon.Inthiscaseyou'llcreateadirectorycalledhellotoholdyourhelloprogram.InUNIX,type:%mkdirhello%cdhelloPage14InMS-DOS,type:C:MKDIRHELLOC:CDHELLOStep2:CreatetheProgramAprogramstartsoutasatextfile.Example2-1showsthehelloprograminsourceform.Example2-1Sourceforthehello.ccprogram #include