CPrimerPlus,FifthEdition
ByStephenPrata
Publisher :Sams
PubDate :November23,2004
ISBN :0-672-32696-5
Pages :984
Tableof
•
Contents
• Index
Aleanrevisionofacomputerindustryclassicthathassoldover
500,000copiesinpreviouseditions.
FifthEditioncontainsover20newprogrammingexercises
andnewlyimprovedexamples.
CandC++accountfor30%ofdevelopers,aboutthree
million,andisa$22millionbookmarketperyear.
UpdatesthethirdeditionbyintegratingnewANSI/ISO
standard,C99.
Classicthatteachesthefundamentalsofprogramming.
CPrimerPlus,FifthEdition
ByStephenPrata
Publisher :Sams
PubDate :November23,2004
Tableof
ISBN :0-672-32696-5
•
Contents
Pages :984
• Index
Copyright
PREFACE
ApproachandGoals
ABOUTTHEAUTHOR
ACKNOWLEDGMENTS
WEWANTTOHEARFROMYOU!
Chapter1.GettingReady
WhenceC?
WhyC?
WhatComputersDo
UsingC:SevenSteps
ProgrammingMechanics
HowThisBookIsOrganized
Summary
WhitherC?
High-levelComputerLanguagesandCompilers
LanguageStandards
ConventionsUsedinThisBook
ReviewQuestions
ProgrammingExercise
Chapter2.IntroducingC
ASimpleExampleofC
TheExampleExplained
TipsonMakingYourProgramsReadable
TheStructureofaSimpleProgram
TakingAnotherStepinUsingC
WhileYou'reatItMultipleFunctions
KeywordsandReservedIdentifiers
Summary
IntroducingDebugging
KeyConcepts
ReviewQuestions
ProgrammingExercises
Chapter3.DataandC
ASampleProgram
DataVariablesandConstants
BasicCDataTypes
ArgumentsandPitfalls
KeyConcepts
ReviewQuestions
Data:Data-TypeKeywords
UsingDataTypes
OneMoreExample:EscapeSequences
Summary
ProgrammingExercises
Chapter4.CharacterStringsandFormattedInput/Output
IntroductoryProgram
CharacterStrings:AnIntroduction
ConstantsandtheCPreprocessor
KeyConcepts
ReviewQuestions
ExploringandExploitingprintf()andscanf()
Summary
ProgrammingExercises
Chapter5.Operators,Expressions,andStatements
IntroducingLoops
FundamentalOperators
SomeAdditionalOperators
TypeConversions
ASampleProgram
Summary
ExpressionsandStatements
FunctionwithArguments
KeyConcepts
ReviewQuestions
ProgrammingExercises
Chapter6.CControlStatements:Looping
RevisitingthewhileLoop
ThewhileStatement
IndefiniteLoopsandCountingLoops
MoreAssignmentOperators:+=,-=,*=,/=,%=
AnExit-ConditionLoop:dowhile
NestedLoops
ALoopExampleUsingaFunctionReturnValue
Summary
WhichIsBigger:UsingRelationalOperatorsandExpressions
TheforLoop
TheCommaOperator
WhichLoop?
IntroducingArrays
KeyConcepts
ReviewQuestions
ProgrammingExercises
Chapter7.CControlStatements:BranchingandJumps
TheifStatement
AddingelsetotheifStatement
AWord-CountProgram
LoopAids:continueandbreak
ThegotoStatement
Summary
Let'sGetLogical
TheConditionalOperator:?:
MultipleChoice:switchandbreak
KeyConcepts
ReviewQuestions
ProgrammingExercises
Chapter8.CharacterInput/OutputandInputValidation
Single-CharacterI/O:getchar()andputchar()
Buffers
RedirectionandFiles
InputValidation
TerminatingKeyboardInput
CreatingaFriendlierUserInterface
MenuBrowsing
KeyConcepts
ReviewQuestions
Summary
ProgrammingExercises
Chapter9.Functions
ReviewingFunctions
ANSICFunctionPrototyping
Recursion
FindingAddresses:The&Operator
Pointers:AFirstLook
Summary
CompilingProgramswithTwoorMoreSourceCodeFiles
AlteringVariablesintheCallingFunction
KeyConcepts
ReviewQuestions
ProgrammingExercises
Chapter10.ArraysandPointers
Arrays
MultidimensionalArrays
Functions,Arrays,andPointers
ProtectingArrayContents
Variable-LengthArrays(VLAs)
KeyConcepts
ReviewQuestions
PointersandArrays
PointerOperations
PointersandMultidimensionalArrays
CompoundLiterals
Summary
ProgrammingExercises
Chapter11.CharacterStringsandStringFunctions
RepresentingStringsandStringI/O
StringInput
StringOutput
StringFunctions
Thectype.hCharacterFunctionsandStrings
TheDo-It-YourselfOption
AStringExample:SortingStrings
Command-LineArguments
String-to-NumberConversions
Summary
KeyConcepts
ReviewQuestions
ProgrammingExercises
Chapter12.StorageClasses,Linkage,andMemoryManagement
StorageClasses
Storage-ClassSpecifiers
ARandom-NumberFunctionandaStaticVariable
AllocatedMemory:malloc()andfree()
KeyConcepts
ReviewQuestions
StorageClassesandFunctions
Roll'Em
ANSICTypeQualifiers
Summary
ProgrammingExercises
Chapter13.FileInput/Output
CommunicatingwithFiles
StandardI/O
ASimple-MindedFile-CondensingProgram
AdventuresinRandomAccess:fseek()andftell()
OtherStandardI/OFunctions
Summary
FileI/O:fprintf(),fscanf(),fgets(),andfputs()
BehindtheSceneswithStandardI/O
KeyConcepts
ReviewQuestions
ProgrammingExercises
Chapter14.StructuresandOtherDataForms
SampleProblem:CreatinganInventoryofBooks
SettingUptheStructureDeclaration
ArraysofStructures
PointerstoStructures
SavingtheStructureContentsinaFile
DefiningaStructureVariable
NestedStructures
TellingFunctionsAboutStructures
Structures:WhatNext?
Unions:AQuickLook
typedef:AQuickLook
FunctionsandPointers
Summary
EnumeratedTypes
FancyDeclarations
KeyConcepts
ReviewQuestions
ProgrammingExercises
Chapter15.BitFiddling
BinaryNumbers,Bits,andBytes
OtherNumberBases
BitFields
Summary
C'sBitwiseOperators
KeyConcepts
ReviewQuestions
ProgrammingExercises
Chapter16.TheCPreprocessorandtheCLibrary
FirstStepsinTranslatingaProgram
ManifestConstants:#define
MacroorFunction?
OtherDirectives
TheCLibrary
TheGeneralUtilitiesLibrary
memcpy()andmemmove()fromthestring.hLibrary
KeyConcepts
ReviewQuestions
UsingArgumentswith#define
FileInclusion:#include
InlineFunctions
TheMathLibrary
TheAssertLibrary
VariableArguments:stdarg.h
Summary
ProgrammingExercises
Chapter17.AdvancedDataRepresentation
ExploringDataRepresentation
BeyondtheArraytotheLinkedList
AbstractDataTypes(ADTs)
SimulatingwithaQueue
BinarySearchTrees
KeyConcepts
ReviewQuestions
GettingQueuedwithanADT
TheLinkedListVersustheArray
OtherDirections
Summary
ProgrammingExercises
AppendixA.AnswerstotheReviewQuesions
AnswerstoReviewQuestionsforChapter1
AnswerstoReviewQuestionsforChapter2
AnswerstoReviewQuestionsforChapter3
AnswerstoReviewQuestionsforChapter5
AnswerstoReviewQuestionsforChapter7
AnswerstoReviewQuestionsforChapter9
AnswerstoReviewQuestionsforChapter11
AnswerstoReviewQuestionsforChapter13
AnswerstoReviewQuestionsforChapter15
AnswerstoReviewQuestionsforChapter4
AnswerstoReviewQuestionsforChapter6
AnswerstoReviewQuestionsforChapter8
AnswerstoReviewQuestionsforChapter10
AnswerstoReviewQuestionsforChapter12
AnswerstoReviewQuestionsforChapter14
AnswerstoReviewQuestionsforChapter16
AnswerstoReviewQuestionsforChapter17
AppendixB.ReferenceSection
SectionI:AdditionalReading
SectionII:COperators
SectionIV:Expressions,Statements,andProgramFlow
SectionVI:ExtendedIntegerTypes
SectionVIII:C99NumericComputationalEnhancements
SectionIII:BasicTypesandStorageClasses
SectionV:TheStandardANSICLibrarywithC99Additions
SectionVII:ExpandedCharacterSupport
SectionIX:DifferencesBetweenCandC++
Index
Copyright
Copyright©2005bySamsPublishing
Allrightsreserved.Nopartofthisbookshallbereproduced,
storedinaretrievalsystem,ortransmittedbyanymeans,
electronic,mechanical,photocopying,recording,orotherwise,
withoutwrittenpermissionfromthepublisher.Nopatent
liabilityisassumedwithrespecttotheuseoftheinformation
containedherein.Althougheveryprecautionhasbeentakenin
thepreparationofthisbook,thepublisherandauthorassume
noresponsibilityforerrorsoromissions.Norisanyliability
assumedfordamagesresultingfromtheuseoftheinformation
containedherein.
LibraryofCongressCatalogCardNumber:2004095068
PrintedintheUnitedStatesofAmerica
FirstPrinting:November,2004
070605044321
Trademarks
Alltermsmentionedinthisbookthatareknowntobe
trademarksorservicemarkshavebeenappropriately
capitalized.SamsPublishingcannotattesttotheaccuracyof
thisinformation.Useofaterminthisbookshouldnotbe
regardedasaffectingthevalidityofanytrademarkorservice
mark.
WarningandDisclaimer
Everyefforthasbeenmadetomakethisbookascompleteand
asaccurateaspossible,butnowarrantyorfitnessisimplied.
Theinformationprovidedisonan"asis"basis.
BulkSales
SamsPublishingoffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales.For
moreinformation,pleasecontact
U.S.CorporateandGovernmentSales
1-800-382-3419
ForsalesoutsideoftheU.S.,pleasecontact
InternationalSales
Credits
ASSOCIATEPUBLISHER
MichaelStephens
ACQUISITIONSEDITOR
LorettaYates
MANAGINGEDITOR
CharlotteClapp
DEVELOPMENTEDITOR
SonglinQiu
PROJECTEDITOR
GeorgeE.Nedeff
COPYEDITOR
BartReed
INDEXER
ChrisBarrick
PROOFREADER
PaulaLowell
TECHNICALEDITOR
GregPerry
PUBLISHINGCOORDINATOR
CindyTeeters
MULTIMEDIADEVELOPER
DanScherf
BOOKDESIGNER
GaryAdair
PAGELAYOUT
BronkellaPublishing
DEDICATION
WithlovetoVickyandBillPrata,who,formorethan69years,
havebeenshowinghowrewardingamarriagecanbe.SP
PREFACE
Cwasarelativelylittle-knownlanguagewhenthefirsteditionof
CPrimerPluswaswrittenin1984.Sincethen,thelanguagehas
boomed,andmanypeoplehavelearnedCwiththehelpofthis
book.Infact,over500,000peoplehavepurchasedCPrimer
Plusthroughoutitsvariouseditions.
AsthelanguagehasgrownfromtheearlyinformalK&R
standardthroughthe1990ISO/ANSIstandardtothe1999
ISO/ANSIstandard,sohasthisbookmaturedthroughthis,the
fifthedition.Aswithalltheeditions,myaimhasbeentocreate
anintroductiontoCthatisinstructive,clear,andhelpful.
ApproachandGoals
Mygoalisforthisbooktoserveasafriendly,easy-to-use,selfstudyguide.Toaccomplishthatobjective,CPrimerPlus
employsthefollowingstrategies:
Programmingconceptsareexplained,alongwithdetailsof
theClanguage;thebookdoesnotassumethatyouarea
professionalprogrammer.
Manyshort,easilytypedexamplesillustratejustoneortwo
conceptsatatime,becauselearningbydoingisoneofthe
mosteffectivewaystomasternewinformation.
Figuresandillustrationsclarifyconceptsthataredifficultto
graspinwordsalone.
HighlightboxessummarizethemainfeaturesofCforeasy
referenceandreview.
Reviewquestionsandprogrammingexercisesattheendof
eachchapterallowyoutotestandimproveyour
understandingofC.
Togainthegreatestbenefit,youshouldtakeasactivearoleas
possibleinstudyingthetopicsinthisbook.Don'tjustreadthe
examples,enterthemintoyoursystem,andtrythem.Cisa
veryportablelanguage,butyoumayfinddifferencesbetween
howaprogramworksonyoursystemandhowitworkson
ours.Experimentchangepartofaprogramtoseewhatthe
effectis.Modifyaprogramtodosomethingslightlydifferent.
Ignoretheoccasionalwarningsandseewhathappenswhen
youdothewrongthing.Trythequestionsandexercises.The
moreyoudoyourself,themoreyouwilllearnandremember.
Ihopethatyou'llfindthisnewesteditionanenjoyableand
effectiveintroductiontotheClanguage.
ABOUTTHEAUTHOR
StephenPratateachesastronomy,physics,andprogramming
attheCollegeofMarininKentfield,California.Hereceivedhis
B.S.fromtheCaliforniaInstituteofTechnologyandhisPh.D.
fromtheUniversityofCalifornia,Berkeley.Hisassociationwith
computersbeganwiththecomputermodelingofstarclusters.
Stephenhasauthoredorcoauthoredoveradozenbooks,
includingC++PrimerPlusandUnixPrimerPlus.
ACKNOWLEDGMENTS
IwishtothankLorettaYatesofSamsPublishingforgettingthis
projectunderwayandSonglinQiuofSamsPublishingforseeing
itthrough.Also,thankyouRonLiechtyofMetrowerksandGreg
ComeauofComeauComputingforyourhelpwithnewC99
featuresandyournoteworthycommitmenttocustomerservice.
WEWANTTOHEARFROMYOU!
Asthereaderofthisbook,youareourmostimportantcritic
andcommentator.Wevalueyouropinionandwanttoknow
whatwe'redoingright,whatwecoulddobetter,whatareas
you'dliketoseeuspublishin,andanyotherwordsofwisdom
you'rewillingtopassourway.
AsanassociatepublisherforSamsPublishing,Iwelcomeyour
comments.Youcanemailorwritemedirectlytoletmeknow
whatyoudidordidn'tlikeaboutthisbookaswellaswhatwe
candotomakeourbooksbetter.
PleasenotethatIcannothelpyouwithtechnicalproblems
relatedtothetopicofthisbook.WedohaveaUserServices
group,however,whereIwillforwardspecifictechnical
questionsrelatedtothebook.
Whenyouwrite,pleasebesuretoincludethisbook'stitleand
authoraswellasyourname,emailaddress,andphonenumber.
Iwillcarefullyreviewyourcommentsandsharethemwiththe
authorandeditorswhoworkedonthebook.
Email:
Mail:
MichaelStephens
AssociatePublisher
SamsPublishing
800East96thStreet
Indianapolis,IN46240USA
FormoreinformationaboutthisbookoranotherSams
Publishingtitle,visitourWebsiteatwww.samspublishing.com.
TypetheISBN(0672326965)orthetitleofabookinthe
Searchfieldtofindthepageyou'relookingfor.
Chapter1.GettingReady
Youwilllearnaboutthefollowinginthischapter:
C'shistoryandfeatures
Thestepsneededtowriteprograms
Abitaboutcompilersandlinkers
Cstandards
WelcometotheworldofCavigorous,professionalprogramming
languagepopularwithamateurandcommercialprogrammers
alike.Thischapterpreparesyouforlearningandusingthis
powerfulandpopularlanguage,anditintroducesyoutothe
kindsofenvironmentsinwhichyouwillmostlikelydevelopyour
C-legs.
First,welookatC'soriginandexaminesomeofitsfeatures,
bothstrengthsanddrawbacks.Thenwelookattheoriginsof
programmingandexaminesomegeneralprinciplesfor
programming.Finally,wediscusshowtorunCprogramson
somecommonsystems.
WhenceC?
DennisRitchieofBellLabscreatedCin1972asheandKen
ThompsonworkedondesigningtheUnixoperatingsystem.C
didn'tspringfull-grownfromRitchie'shead,however.Itcame
fromThompson'sBlanguage,whichcamefrom…butthat's
anotherstory.TheimportantpointisthatCwascreatedasa
toolforworkingprogrammers,soitschiefgoalistobeauseful
language.
Mostlanguagesaimtobeuseful,buttheyoftenhaveother
concerns.ThemaingoalforPascal,forinstance,wastoprovide
asoundbasisforteachinggoodprogrammingprinciples.BASIC,
ontheotherhand,wasdevelopedtoresembleEnglishsothatit
couldbelearnedeasilybystudentsunfamiliarwithcomputers.
Theseareimportantgoals,buttheyarenotalwayscompatible
withpragmatic,workadayusefulness.C'sdevelopmentasa
languagedesignedforprogrammers,however,hasmadeitone
ofthemodern-daylanguagesofchoice.
WhyC?
Duringthepastthreedecades,Chasbecomeoneofthemost
importantandpopularprogramminglanguages.Ithasgrown
becausepeopletryitandlikeit.Inthepastdecade,manyhave
movedfromCtothemoreambitiousC++language,butCis
stillanimportantlanguageinitsownright,aswellamigration
pathtoC++.AsyoulearnC,youwillrecognizeitsmanyvirtues
(seeFigure1.1).Let'spreviewafewofthemnow.
Figure1.1.ThevirtuesofC.
DesignFeatures
Cisamodernlanguageincorporatingthecontrolfeaturesfound
desirablebythetheoryandpracticeofcomputerscience.Its
designmakesitnaturalfortop-downplanning,structured
programming,andmodulardesign.Theresultisamore
reliable,understandableprogram.
Efficiency
Cisanefficientlanguage.Itsdesigntakesadvantageofthe
capabilitiesofcurrentcomputers.Cprogramstendtobe
compactandtorunquickly.Infact,Cexhibitssomeofthefine
controlusuallyassociatedwithanassemblylanguage.(An
assemblylanguageisamnemonicrepresentationofthesetof
internalinstructionsusedbyaparticularcentralprocessingunit
design;differentCPUfamilieshavedifferentassembly
languages.)Ifyouchoose,youcanfine-tuneyourprogramsfor
maximumspeedormostefficientuseofmemory.
Portability
Cisaportablelanguage,whichmeansthatCprogramswritten
ononesystemcanberunonothersystemswithlittleorno
modification.Ifmodificationsarenecessary,theycanoftenbe
madebysimplychangingafewentriesinaheaderfile
accompanyingthemainprogram.Mostlanguagesaremeantto
beportable,butanyonewhohasconvertedanIBMPCBASIC
programtoAppleBASIC(andtheyareclosecousins)orhas
triedtorunanIBMmainframeFORTRANprogramonaUnix
systemknowsthatportingistroublesomeatbest.Cisaleader
inportability.Ccompilers(programsthatconvertyourCcode
intotheinstructionsacomputerusesinternally)areavailable
forabout40systems,runningfrom8-bitmicroprocessorsto
Craysupercomputers.Note,however,thattheportionsofa
programwrittenspecificallytoaccessparticularhardware
devices,suchasadisplaymonitor,orspecialfeaturesofan
operatingsystem,suchasWindowsXPorOSX,typicallyare
notportable.
BecauseofC'sclosetieswithUnix,Unixsystemstypicallycome
withaCcompileraspartofthepackages.Linuxinstallations
alsousuallyincludeaCcompiler.SeveralCcompilersare
availableforpersonalcomputers,includingPCsrunningvarious
versionsofWindows,andMacintoshes.Sowhetheryouare
usingahomecomputer,aprofessionalworkstation,ora
mainframe,thechancesaregoodthatyoucangetaCcompiler
foryourparticularsystem.
PowerandFlexibility
Cispowerfulandflexible(twofavoritewordsincomputer
literature).Forexample,mostofthepowerful,flexibleUnix
operatingsystemiswritteninC.Manycompilersand
interpretersforotherlanguagessuchasFORTRAN,Perl,Python,
Pascal,LISP,Logo,andBASIChavebeenwritteninC.Asa
result,whenyouuseFORTRANonaUnixmachine,ultimatelya
Cprogramhasdonetheworkofproducingthefinalexecutable
program.Cprogramshavebeenusedforsolvingphysicsand
engineeringproblemsandevenforanimatingspecialeffectsfor
moviessuchasGladiator.
ProgrammerOriented
Cisorientedtofulfilltheneedsofprogrammers.Itgivesyou
accesstohardware,anditenablesyoutomanipulateindividual
bitsinmemory.Ithasarichselectionofoperatorsthatallows