CPrimerPlus,FourthEdition
ByStephenPrata
Publisher :SamsPublishing
PubDate :September19,2001
Tableof
ISBN :0-672-32222-6
•
Contents
Pages :960
• Index
Copyright
PREFACE
ApproachandGoals
Changesinthe4thEdition
ABOUTTHEAUTHOR
ACKNOWLEDGMENTS
TELLUSWHATYOUTHINK!
Chapter1.GettingReady
WhenceC?
WhyC?
WhitherC?
WhatComputersDo
High-LevelComputerLanguagesandCompilers
UsingC:SevenSteps
ProgrammingMechanics
LanguageStandards
BookOrganization
SomeConventions
Summary
ReviewQuestions
ProgrammingExercise
Chapter2.IntroducingC
ASimpleSampleofC
TheExplanation
TheStructureofaSimpleProgram
TipsonMakingYourProgramsReadable
TakingAnotherStep
WhileYou'reatIt…MultipleFunctions
Debugging
KeywordsandReservedIdentifiers
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter3.DataandC
ASampleProgram
DataVariablesandConstants
Data:Data-TypeKeywords
CDataTypes
UsingDataTypes
ArgumentsandPitfalls
OneMoreExample
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter4.CharacterStringsandFormattedInput/Output
IntroductoryProgram
CharacterStrings:AnIntroduction
ConstantsandtheCPreprocessor
ExploringandExploitingprintf()andscanf()
UsageTips
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter5.Operators,Expressions,andStatements
IntroducingLoops
FundamentalOperators
SomeAdditionalOperators
ExpressionsandStatements
TypeConversions
FunctionwithArguments
ASampleProgram
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter6.CControlStatements:Looping
AnInitialExample
ThewhileStatement
WhichIsBigger:UsingRelationalOperatorsandExpressions
IndefiniteLoopsandCountingLoops
TheforLoop
MoreAssignmentOperators:+=,-=,*=,/=,%=
TheCommaOperator
AnExit-ConditionLoop:dowhile
WhichLoop?
NestedLoops
Arrays
ALoopExampleUsingaFunctionReturnValue
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter7.CControlStatements:BranchingandJumps
TheifStatement
AddingelsetotheifStatement
Let'sGetLogical
AWord-CountProgram
TheConditionalOperator:?
LoopAids:continueandbreak
MultipleChoice:switchandbreak
ThegotoStatement
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter8.CharacterInput/OutputandInputValidation
Single-CharacterI/O:getchar()andputchar()
Buffers
TerminatingKeyboardInput
RedirectionandFiles
CreatingaFriendlierUserInterface
InputValidation
MenuBrowsing
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter9.Functions
ReviewingFunctions
ANSICFunctionPrototyping
Recursion
AllCFunctionsAreCreatedEqual
CompilingProgramswithTwoorMoreSourceCodeFiles
FindingAddresses:The&Operator
AlteringVariablesintheCallingFunction
Pointers:AFirstLook
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter10.ArraysandPointers
Arrays
MultidimensionalArrays
PointersandArrays
Functions,Arrays,andPointers
PointerOperations
ProtectingArrayContents
PointersandMultidimensionalArrays
Variable-LengthArrays(VLAs)
CompoundLiterals
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter11.CharacterStringsandStringFunctions
DefiningStringsWithinaProgram
CharacterStringArraysandInitialization
StringInput
StringOutput
TheDo-It-YourselfOption
StringFunctions
AStringExample:SortingStrings
Thectype.hCharacterFunctionsandStrings
Command-LineArguments
StringtoNumberConversions
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter12.StorageClasses,Linkage,andMemoryManagement
StorageClasses
ARandomNumberFunctionandaStaticVariable
Roll'Em
ANSICTypeQualifiers
NewPlacesforOldKeywords
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter13.FileInput/Output
CommunicatingwithFiles
StandardI/O
ASimple-MindedFile-CondensingProgram
FileI/O:fprintf(),fscanf(),fgets(),andfputs()
AdventuresinRandomAccess:fseek()andftell()
BehindtheSceneswithStandardI/O
OtherStandardI/OFunctions
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter14.StructuresandOtherDataForms
SampleProblem:CreatinganInventoryofBooks
SettingUptheStructureDeclaration
DefiningaStructureVariable
GainingAccesstoStructureMembers
ArraysofStructures
NestedStructures
PointerstoStructures
TellingFunctionsAboutStructures
SavingtheStructureContentsinaFile
Structures:WhatNext?
Unions:AQuickLook
EnumeratedTypes
typedef:AQuickLook
FancyDeclarations
FunctionsandPointers
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter15.BitFiddling
BinaryNumbers,Bits,andBytes
OtherBases
C'sBitwiseOperators
BitFields
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter16.TheCPreprocessorandtheCLibrary
FirstSteps
ManifestConstants:#define
UsingArgumentswith#define
MacroorFunction?
FileInclusion:#include
OtherDirectives
InlineFunctions
TheCLibrary
TheMathLibrary
TheGeneralUtilitiesLibrary
TheAssertLibrary
memcpy()andmemmove()fromthestring.hLibrary
VariableArguments:stdarg.h
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
Chapter17.AdvancedDataRepresentation
ExploringDataRepresentation
BeyondtheArraytotheLinkedList
AbstractDataTypes(ADTs)
GettingQueuedwithanADT
SimulatingwithaQueue
TheLinkedListVersustheArray
BinarySearchTrees
OtherDirections
KeyConcepts
Summary
ReviewQuestions
ProgrammingExercises
AppendixA.AnswerstotheReviewQuestions
Chapter1
Chapter2
Chapter3
Chapter4
Chapter5
Chapter6
Chapter7
Chapter8
Chapter9
Chapter10
Chapter11
Chapter12
Chapter13
Chapter14
Chapter15
Chapter16
Chapter17
AppendixB.ReferenceSection
SectionIAdditionalReading
SectionIICOperators
LogicalOperators
SignOperators
SectionIIIBasicTypesandStorageClasses
Summary:Qualifiers
SectionIVExpressions,Statements,andProgramFlow
SectionVTheStandardANSICLibrarywithC99Additions
MathLibrary:math.h
VariableArguments:stdarg.h
StandardI/OLibrary:stdio.h
GeneralUtilities:stdlib.h
SectionVIExtendedIntegerTypes
SectionVIIExpandedCharacterSupport
SectionVIIIC99NumericComputationalEnhancements
SectionIXDifferencesBetweenCandC++
Top
Index
CPrimerPlus,FourthEditionByStephenPrata
TableofContents
Copyright
Copyright©2002bySamsPublishing
Allrightsreserved.Nopartofthisbookshallbe
reproduced,storedinaretrievalsystem,or
transmittedbyanymeans,electronic,mechanical,
photocopying,recording,orotherwise,without
writtenpermissionfromthepublisher.Nopatent
liabilityisassumedwithrespecttotheuseofthe
informationcontainedherein.Althoughevery
precautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorassumeno
responsibilityforerrorsoromissions.Norisany
liabilityassumedfordamagesresultingfromtheuse
oftheinformationcontainedherein.
LibraryofCongressCatalogCardNumber:
2001089225
PrintedintheUnitedStatesofAmerica
FirstPrinting:September2001
030201004321
Trademarks
Alltermsmentionedinthisbookthatareknowntobe
trademarksorservicemarkshavebeenappropriately
capitalized.SamsPublishingcannotattesttothe
accuracyofthisinformation.Useofaterminthis
bookshouldnotberegardedasaffectingthevalidity
ofanytrademarkorservicemark.
AppleisaregisteredtrademarkofAppleComputer,
Inc.
BorlandC++isaregisteredtrademarkofBorland
International,Inc.
CodeWarriorisaregisteredtrademarkofMetrowerks,
Inc.
CrayisaregisteredtrademarkofCrayComputer,Inc.
IBMandPCareregisteredtrademarksandPCDOSis
atrademarkoftheInternationalBusinessMachines
Company.
MacintoshisaregisteredtrademarkofMacintosh
Laboratory,Inc.,licensedbyAppleComputer,Inc.
MicrosoftandMS-DOSareregisteredtrademarksof
MicrosoftCorporation.
PrimerPlusisaregisteredtrademarkofTheWaite
Group,Inc.
ThinkCisaregisteredtrademarkofSymantec
Corporation.
TurboCisaregisteredtrademarkofBorland
International,Inc.
UnixisatrademarkofAmericanTelephoneand
TelegraphCorporation.
VAXisaregisteredtrademarkandVMSisa
trademarkofDigitalEquipmentCorporation.
WindowsisaregisteredtrademarkofMicrosoft
Corporation.
WordPerfectisaregisteredtrademarkofWordPerfect
Corporation.
WordStarisaregisteredtrademarkofMicroPro
InternationalCorporation.
WarningandDisclaimer
Everyefforthasbeenmadetomakethisbookas
completeandasaccurateaspossible,butnowarranty
orfitnessisimplied.Theinformationprovidedison
an"asis"basis.Theauthorandthepublishershall
haveneitherliabilitynorresponsibilitytoanyperson
orentitywithrespecttoanylossordamagesarising
fromtheinformationcontainedinthisbookorfrom
theuseoftheWebsiteorprogramsaccompanyingit.
Credits
ASSOCIATEPUBLISHER
LindaEngelman
ACQUISITIONSEDITORS
LindaScharp
KarenWachs
DEVELOPMENTEDITOR
KarenWachs
MANAGINGEDITOR
CharlotteClapp
PROJECTEDITOR
SheilaSchroeder
COPYEDITOR
PatKinyon
INDEXER
SandraHenselmeier
PROOFREADER
Plan-ItPublishing
TECHNICALEDITOR
JeffPerkins
ChrisMaunder
TEAMCOORDINATORS
ChrisFeather
LynneWilliams
MEDIADEVELOPER
DanScherf
INTERIORDESIGNER
GaryAdair
PAGELAYOUT
TimOsborn
DEDICATION
WithlovetoVickyandBillPrata,who,formorethan
65years,havebeenshowinghowrewardinga
marriagecanbe.SP
Top
CPrimerPlus,FourthEditionByStephenPrata
TableofContents
PREFACE
Cwasarelativelylittle-knownlanguagewhenthe
firsteditionofCPrimerPluswaswrittenin1984.
Sincethen,thelanguagehasboomed,andmany
peoplehavelearnedCwiththehelpofthisbook.In
fact,over500,000peoplehavepurchasedCPrimer
Plusthroughoutitsvariouseditions.
WiththeemergenceofanewstandardforC,it'stime
fora4thedition.Aswithalltheeditions,myaimhas
beentocreateanintroductiontoCthatisinstructive,
clear,andhelpful.
Top
CPrimerPlus,FourthEditionByStephenPrata
TableofContents
PREFACE
ApproachandGoals
Mygoalisforthisbooktoserveasafriendly,easyto-use,self-studyguide.Toaccomplishthatobjective,
CPrimerPlusemploysthefollowingstrategies:
Programmingconceptsareexplained,alongwith
detailsoftheClanguage;thebookdoesnot
assumethatyouareaprofessionalprogrammer.
Manyshort,easily-typedexamplesillustratejust
oneortwoconceptsatatime,becauselearningby
doingisoneofthemosteffectivewaystomaster
newinformation.
Figuresandillustrationsclarifyconceptsthatare
difficulttograspinwordsalone.
HighlightboxessummarizethemainfeaturesofC
foreasyreferenceandreview.
Reviewquestionsandprogrammingexercisesat
theendofeachchapterallowyoutotestand
improveyourunderstandingofC.
Togainthegreatestbenefit,youshouldtakeasactive
aroleaspossibleinstudyingthetopicsinthisbook.
Don'tjustreadtheexamples,enterthemintoyour
systemandtrythem.Cisaveryportablelanguage,
butyoumayfinddifferencesbetweenhowaprogram
worksonyoursystemandhowitworksonours.
Experimentchangepartofaprogramtoseewhatthe
effectis.Modifyaprogramtodosomethingslightly
different.Ignoretheoccasionalwarningsandseewhat
happenswhenyoudothewrongthing.Trythe
questionsandexercises.Themoreyoudoyourself,
themoreyouwilllearnandremember.
Ihopethatyou'llfindthisnewesteditionanenjoyable
andeffectiveintroductiontotheClanguage.
Top
CPrimerPlus,FourthEditionByStephenPrata
TableofContents
PREFACE
Changesinthe4thEdition
ThereisanewstandardfortheClanguage.It'scalled
theISO/IEC9899:1999InternationalStandard,but
amongfriendsitoftengoesbythesimplernameof
C99.ItwasadoptedbytheInternationalOrganization
forStandardization(ISO)andtheInternational
ElectrotechnicalCommittee(IEC)in1999and
approvedastheAmericanstandardbytheAmerican
NationalStandardsInstitute(ANSI)in2000.This
neweditionof>CPrimerPlusincorporatesthenew
standard.Herearesomeofthenewfeaturescovered:
Extendedintegertypes
Expandedcharactersupport
Booleansupport
Variable-lengtharrays
Compoundliterals
Designatedinitializers
Expandedcomputationalsupport
Inlinefunctions
Thiseditionalsoreorganizesthepresentationofsome
topics.Forexample,thediscussionofpointersin
Chapter10,"ArraysandPointers,"hasbeen
consolidatedandexpanded,andChapter12,"Storage
Classes,Linkage,andMemoryManagement,"
incorporatesdynamicmemoryallocationintothe
discussionofCstorageclassesandmemory
management.Numerousotherchangesandadditions
havebeenincorporatedinresponsetoreaderrequests
tomakethiseditionanevenmoreeffectivelearning
tool.
Top
CPrimerPlus,FourthEditionByStephenPrata
TableofContents
ABOUTTHEAUTHOR
StephenPrataisaprofessorofphysicsand
astronomyattheCollegeofMarininKentfield,
California,whereheteachesastronomy,physics,and
programming.HereceivedhisB.S.fromthe
CaliforniaInstituteofTechnologyandhisPh.D.from
theUniversityofCalifornia,Berkeley.Hisassociation
withcomputersbeganwiththecomputermodelingof
starclusters.Stephenhasauthoredorcoauthoredover
adozenbooks,includingC++PrimerPlusandUnix
PrimerPlus.
Top
CPrimerPlus,FourthEditionByStephenPrata
TableofContents
ACKNOWLEDGMENTS
IwishtothankLindaScharpofSamsPublishingfor
gettingthisprojectunderwayandKarenWachsof
SamsPublishingforseeingitthrough.Also,thank
youRonLiechtyofMetrowerksandGregComeauof
ComeauComputingforyourhelpwithnewC99
featuresandyournoteworthycommitmentto
customerservice.
Top
CPrimerPlus,FourthEditionByStephenPrata
TableofContents