C Programming
C Programming
CProgramming/Printversion
CProgramming
Thecurrent,editableversionofthisbookisavailableinWikibooks,theopencontenttextbookscollection,at http://en.wikibooks.org/wiki/C_Programming
Permissionisgrantedtocopy,distribute,and/ormodifythisdocumentunderthetermsoftheCreativeCommonsAttributionShareAlike3.0License.
WhylearnC?
Cisthemostcommonlyusedprogramminglanguageforwritingoperatingsystems.UnixwasthefirstoperatingsystemwritteninC.LaterMicrosoftWindows,MacOSX,andGNU/LinuxwereallwritteninC.NotonlyisCthelanguageofoperating systems,itistheprecursorandinspirationforalmostallofthemostpopularhighlevellanguagesavailabletoday.Infact,Perl,PHP,andPythonareallwritteninC. Bywayofanalogy,let'ssaythatyouweregoingtobelearningSpanish,Italian,French,orPortuguese.DoyouthinkknowingLatinwouldbehelpful?JustasLatinwasthebasisofallofthoselanguages,knowingCwillenableyoutounderstandand appreciateanentirefamilyofprogramminglanguagesbuiltuponthetraditionsofC.KnowledgeofCenablesfreedom.
WhyC,andnotassemblylanguage?
Whileassemblylanguagecanprovidespeedandmaximumcontroloftheprogram,Cprovidesportability. DifferentprocessorsareprogrammedusingdifferentAssemblylanguagesandhavingtochooseandlearnonlyoneofthemistooarbitrary.Infact,oneofthemainstrengthsofCisthatitcombinesuniversalityandportabilityacrossvariouscomputer architectureswhileretainingmostofthecontrolofthehardwareprovidedbyassemblylanguage. Forexample,CprogramscanbecompiledandrunontheHP50gcalculator(ARMprocessor),theTI89calculator(68000processor),PalmOSCobaltsmartphones(ARMprocessor),theoriginaliMac(PowerPC),theArduino(AtmelAVR),andtheIntel iMac(IntelCore2Duo).Eachofthesedeviceshasitsownassemblylanguagethatiscompletelyincompatiblewiththeassemblylanguageofanyother. Assembly,whileextremelypowerful,issimplytoodifficulttoprogramlargeapplicationsandhardtoreadorinterpretinalogicalway.Cisacompiledlanguage,whichcreatesfastandefficientexecutablefiles.Itisalsoasmall"whatyouseeisallyou get"language:aCstatementcorrespondstoatmostahandfulofassemblystatements,everythingelseisprovidedbylibraryfunctions. SoisitanywonderthatCissuchapopularlanguage? Liketopplingdominoes,thenextgenerationofprogramsfollowsthetrendofitsancestors.OperatingsystemsdesignedinCalwayshavesystemlibrariesdesignedinC.Thosesystemlibrariesareinturnusedtocreatehigherlevellibraries(likeOpenGL, orGTK),andthedesignersofthoselibrariesoftendecidetousethelanguagethesystemlibrariesused.Applicationdevelopersusethehigherlevellibrariestodesignwordprocessors,games,mediaplayersandthelike.Manyofthemwillchooseto programinthelanguagethatthehigherlevellibraryuses.Andthepatterncontinuesonandonandon......
WhyC,andnotanotherlanguage?
TheprimarydesignofCistoproduceportablecodewhilemaintainingperformanceandminimizingfootprint,asisthecaseforoperatingsystemsorotherprogramswherea"highlevel"interfacewouldaffectperformance.Itisastableandmature languagewhosefeaturesareunlikelytodisappearforalongtimeandhasbeenportedtomost,ifnotall,platforms. Forexample,CprogramscanbecompiledandrunontheHP50gcalculator(ARMprocessor),theTI89calculator(68000processor),PalmOSCobaltsmartphones(ARMprocessor),theoriginaliMac(PowerPC),theArduino(AtmelAVR),andtheIntel iMac(IntelCore2Duo).Whilenearlyallpopularprogramminglanguageswillrunonatleastoneofthesedevices,Cmaybetheonlyprogramminglanguagethatrunsonmorethan3ofthesedevices. Onepowerfulreasonismemoryallocation.Unlikemostcomputerlanguages,Callowstheprogrammertowritedirectlytomemory.KeyconstructsinCsuchasstructs,pointersandarraysaredesignedtostructure,andmanipulatememoryinanefficient, machineindependentfashion.Inparticular,Cgivescontroloverthememorylayoutofdatastructures.Moreoverdynamicmemoryallocationisunderthecontroloftheprogrammer,whichinevitablymeansthatmemorydeallocationistheburdenofthe programmer.LanguageslikeJavaandPerlshieldtheprogrammerfromhavingtoworryaboutmemoryallocationandpointers.Thisisusuallyagoodthing,sincedealingwithmemoryallocationwhenbuildingahighlevelprogramisahighlyerrorprone process.However,whendealingwithlowlevelcodesuchasthepartoftheOSthatcontrolsadevice,Cprovidesauniform,cleaninterface.ThesecapabilitiesjustdonotexistinotherlanguagessuchasJava. WhilePerl,PHP,PythonandRubymaybepowerfulandsupportmanyfeaturesnotprovidedbydefaultinC,theyarenotnormallyimplementedintheirownlanguage.Rather,mostsuchlanguagesinitiallyreliedonbeingwritteninC(oranotherhigh performanceprogramminglanguage),andwouldrequiretheirimplementationbeportedtoanewplatformbeforetheycanbeused. Aswithallprogramminglanguages,whetheryouwanttochooseCoveranotherhighlevellanguageisamatterofopinionandbothtechnicalandbusinessrequirements.
en.wikibooks.org/wiki/C_Programming/Print_version
1/118
10/24/13
History
Thefieldofcomputingasweknowittodaystartedin1947withthreescientistsatBellTelephoneLaboratoriesWilliamShockley,WalterBrattain,andJohnBardeenandtheirgroundbreakinginvention:thetransistor.In1956,thefirstfullytransistor basedcomputer,theTX0,wascompletedatMIT.Thefirstintegratedcircuitwascreatedin1958byJackKilbyatTexasInstruments,butthefirsthighlevelprogramminglanguageexistedevenbeforethen. "TheFortranproject"wasoriginallydevelopedin1954byIBM.Ashorteningof" TheIBMMathematical Formula TranslatingSystem",theprojecthadthepurposeofcreatingandfosteringdevelopmentofaprocedural,imperativeprogramminglanguage thatwasespeciallysuitedtonumericcomputationandscientificcomputing.Itwasabreakthroughintermsofproductivityandprogrammingease(comparedtoassemblylanguage)andspeed(Fortranprogramsrannearlyasfastas,andinsomecases, justasfastas,programswritteninassembly).Furthermore,Fortranwaswrittenatahighenoughlevel(andthuswasmachineindependentenough)tobecomethefirstwidelyadoptedprogramminglanguage.TheAlgorithmicLanguage(Algol58)was derivedfromFortranin1958andevolvedintoAlgol60in1960.TheCombinedProgrammingLanguage(CPL)wasthencreatedoutofAlgol60in1963.In1967,itevolvedintoBasicCPL,whichwasitself,thebaseforBin1969.Finally,Bwastheroot ofC,createdin1971. BwasthefirstlanguageinC'sdirectlineage.BwascreatedbyKenThompsonatBellLabsandwasaninterpretedlanguageusedinearlyinternalversionsoftheUNIXoperatingsystem.ThompsonandDennisRitchie,alsoworkingatBellLabs, improvedBandcalledtheresultNB.FurtherextensionstoNBcreateditslogicalsuccessor,C,acompiledlanguage.MostofUNIXwasrewritteninNB,andthenC,whichresultedinamoreportableoperatingsystem. TheportabilityofUNIXwasthemainreasonfortheinitialpopularityofbothUNIXandC.Ratherthancreatinganewoperatingsystemforeachnewmachine,systemprogrammerscouldsimplywritethefewsystemdependentpartsrequiredforthe machine,andthenwriteaCcompilerforthenewsystem.SincemostofthesystemutilitieswerethuswritteninC,itsimplymadesensetoalsowritenewutilitiesinC. TheAmericanNationalStandardsInstitutebeganworkonstandardizingtheClanguagein1983,andcompletedthestandardin1989.Thestandard,ANSIX3.1591989"ProgrammingLanguageC",servedasthebasisforallimplementationsofC compilers.Thestandardswerelaterupdatedin1990and1999,allowingforfeaturesthatwereeitherincommonuse,orwereappearinginC++.
Whatyouneedbeforeyoucanlearn
GettingStarted
ThegoalofthisbookistointroduceyoutotheCprogramminglanguage.Basiccomputerliteracyisassumed,butnospecialknowledgeisneeded. BeforeyoucanstartprogramminginC,youwillneeda Ccompiler.AcompilerisaprogramthatconvertsCcodeintoexecutablemachinecode. [1] PopularCcompilersInclude: Name MicrosoftVisual StudioExpress TinyCCompiler (TCC) Clang GNUCCompiler Website VisualStudio(http://www.microsoft.com/visualstudio/en us/products/2010editions/visualcppexpress) tinycc(http://www.tinycc.org) clang(http://clang.llvm.org) gcc(http://gcc.gnu.org) Platform Windows GNU/Linux,Windows GNU/Linux,Windows,Unix,OSX GNU/Linux,MinGW(Windows) (http://mingw.org),Unix,OSX. License FreeVersion LGPL UniversityofIllinois/NCSALicense (http://opensource.org/licenses/UoINCSA.php) GPL Details Powerfulandstudentfriendlyversionofan industrystandardcompiler. Small,fastandsimplecompiler. Afrontendwhichcompiles(Objective)C/C++ usingaLLVMbackend. TheDefactostandard.ShipswithmostUnix systems.
TheminimumsoftwarerequirementstoprograminCisatexteditor,asopposedtoawordprocessor.AplaintextNotepadEditorcanbeusedbutitdoesnotofferanyadvancedcapabilitiessuchascodecompletionordebugging.Therearemanytext editors(seeListofTextEditors),amongthemostpopularareNotepad++forWindows,SublimeText,VimandEmacsarealsoavailablecrossplatform.Thesetexteditorscomewithsyntaxhighlightingandlinenumbers,whichmakescodeeasiertoread ataglance,andtospotsyntaxerrors. Thoughnotabsolutelyneeded,manyprogrammerspreferandrecommendusinganIntegrateddevelopmentenvironment(IDE )insteadofatexteditor.AnIDEisasuiteofprogramsthatdevelopersneed,combinedintooneconvenientpackage,usually withagraphicaluserinterface.Theseprogramsincludeatexteditor,linker,projectmanagementandsometimesbundledwithacompiler.Theyalsotypicallyincludeadebugger,atoolthatwillpreserveyourCsourcecodeaftercompilationandenable youtodosuchthingsasstepthroughitmanually,oralterdataasanaidtofindingandcorrectingprogrammingerrors. ForbeginnersitisrecommendednottouseanIDE,sinceithidesmostofwhatisgoingon.Usingthecommandlinebuildsupfamiliaritywiththetoolchain.AnIDEmaybeusefultosomebodywithprogrammingexperiencebutknowshowtheIDEworks. Soasageneralguideline:DonotuseanIDEunlessyouknowwhattheIDEdoes! PopularIDEsInclude: Name EclipseCDT Netbeans Anjuta Geany LittleCCompiler(LCC) Website Platform License Opensource CDDLandGPL2.0 GPL GPL Details EclipseIDEforC/C++developement,apopularopensourceIDE. AGoodcomparablematuredIDEtoEclipse. AGTK+2IDEfortheGNOMEdesktopenvironment. AlightweightcrossplatformGTK+notepadbasedonScintilla,withbasicIDEfeatures.
Windows,MacOSX, Eclipse(http://www.eclipse.org/downloads/packages/eclipseideccdevelopers/junor) Linux Netbeans(http://netbeans.org) Anjuta(http://anjuta.org) geany(http://www.geany.org) lcc(http://www.cs.virginia.edu/~lccwin32) Crossplatform Linux Crossplatform Windows
en.wikibooks.org/wiki/C_Programming/Print_version
2/118
10/24/13
Xcode PellesC DevC++ MicrosoftVisualStudio Express CodeLite Code::Blocks Xcode(https://developer.apple.com/xcode) PellesC(http://smorgasbordet.com/pellesc) DevC++(http://sourceforge.net/projects/orwelldevcpp/)
Footnotes
1. Actually,GCC's(GNUCCompiler) cc(CCompiler)translatestheinput.cfiletothetargetcpu'sassembly,outputiswrittentoan.sfile.Then as(assembler)generatesamachinecodefilefromthe.sfile.Preprocessingisdonebyanothersub program cpp(CPreProcessor),whichisnottobeconfusedwith c++thecompiler. 2. http://sourceforge.net/news/?group_id=10639 3. http://orwelldevcpp.blogspot.com/
UsingaCompiler
DevC++
DevC++isanIntegratedDevelopmentEnvironment(IDE)fortheC++programminglanguage,availablefromBloodshedSoftware(http://www.bloodshed.net/).AnupdatedversionisavailableatOrwellDevC++(http://orwelldevcpp.blogspot.com/). C++isaprogramminglanguagewhichcontainswithinitself,mostoftheClanguage,plusextensions.MostC++compilerswillcompileCprograms,sometimeswithafewadjustments(likeinvokingthemwithadifferentnameorcommandlineswitch). Therefore,youcanuseDevC++forCdevelopment. However,DevC++isnotthecompiler.ItisdesignedtousetheMinGWorCygwinversionsofGCCbothofwhichcanbeobtainedaspartoftheDevC++package,althoughtheyarecompletelydifferentprojects. DevC++simplyprovidesaneditor,syntaxhighlighting,somefacilitiesforthevisualisationofcode(likeclassandpackagebrowsing)andagraphicalinterfacetothechosencompiler.BecauseDevC++analysestheerrormessagesproducedbythe compilerandattemptstodistinguishthelinenumbersfromtheerrorsthemselves,theuseofothercompilersoftwareisdiscouragedsincetheformatoftheirerrormessagesislikelytobedifferent. ThelatestversionofDevC++isabetaforversion5.However,itstillhasasignificantnumberofbugs.Allthefeaturesarethere,anditisquiteusable.ItisconsideredoneofthebestfreesoftwareCIDEsavailableforWindows. AversionofDevC++forLinuxisinthepipeline.Itisnotquiteusableyet,however.LinuxusersalreadyhaveawealthofIDEsavailable.(e.g.KDevelopandAnjuta.)Mostofthegraphicaltexteditors,andothercommoneditorssuchas emacsand vi(m), supportsyntaxhighlighting.
GCC
TheGNUCompilerCollection(GCC)isafreesetofcompilersdevelopedbytheFreeSoftwareFoundation.
StepsforObtainingtheGCCCompilerifYou'reonGNU/Linux On GNU/Linux, InstallingtheGNUCCompilercanvaryinmethodfromdistributiontodistribution.(Typein ccvtoseeifitisinstalledalready.) ForRedhat,getaGCCRPM,e.g.usingRpmfindandtheninstall(asroot)using r p mi v hg c c v e r s i o n r e l e a s e . a r c h . r p m ForFedoraCore,installtheGCCcompiler(asroot)byusing y u mi n s t a l lg c c . ForMandrake,installtheGCCcompiler(asroot)byusing u r p m ig c c ForDebian,installtheGCCcompiler(asroot)byusing a p t g e ti n s t a l lg c c . ForUbuntu,installtheGCCcompiler(alongwithothernecessarytools)byusing s u d oa p t g e ti n s t a l lb u i l d e s s e n t i a l ,orbyusingSynaptic.YoudonotneedUniverseenabled. ForSlackware,thepackageisavailableontheirwebsite(http://www.slackware.com/pb/)simplydownload,andtype i n s t a l l p k gg c c x x x x x . t g z ForGentoo,youshouldalreadyhaveGCCinstalledasitwillhavebeenusedwhenyoufirstinstalled.Toupdateitrun(asroot) e m e r g eu a vg c c . ForArchLinux,installtheGCCcompiler(asroot)byusing p a c m a nSg c c . Ifyoucannotbecomeroot,gettheGCCtarballfromftp://ftp.gnu.org/andfollowtheinstructionsinittocompileandinstallinyourhomedirectory.Bewarnedthough,youneedaCcompilertodothatyes,GCCitselfiswritteninC. YoucanusesomecommercialCcompiler/IDE.
en.wikibooks.org/wiki/C_Programming/Print_version
3/118
10/24/13
StepsforObtainingtheGCCCompilerifYou'reonBSDFamilySystems ForMacOSX,FreeBSD,NetBSD,OpenBSD,DragonFlyBSD,DarwintheportofGNUgccisavailableinthebasesystem,oritcouldbeobtainedusingtheportscollectionorpkgsrc.
StepsforObtainingtheGCCCompilerifYou'reonWindows TherearetwowaystouseGCConWindows:CygwinandMinGW.ApplicationscompiledwithCygwinwillnotrunonanycomputerwithoutCygwin,soMinGWisrecommended.MinGWissimplertoinstall,andtakeslessdiskspace. TogetMinGW,dothis: 1. Gotohttp://sourceforge.net/projects/mingw/downloadandsavethistoyourharddrive. 2. Oncethedownloadisfinished,openitandfollowtheinstructions.Youcanalsochoosetoinstalladditionalcompilers,orthetoolMake,butthesearen'tnecessary. 3. NowyouneedtosetyourPATH.Rightclickon"Mycomputer"andclick"Properties".Gotothe"Advanced"tabandclickon"Environmentvariables".Gotothe"Systemvariables"sectionandscrolldownuntilyousee"Path".Clickonit,thenclick "edit".Add"C:\mingw\bin\"(withoutthequotes)totheend. 4. TotestifGCCworks,openacommandpromptandtype"gcc".Youshouldgetthemessage"gcc:noinputfiles".Ifyougetthismessage,GCCisinstalledcorrectly. TogetCygwin,dothis: 1. 2. 3. 4. Gotohttp://www.cygwin.comandclickonthe"InstallCygwinNow"buttonintheupperrightcornerofthepage. Click"run"inthewindowthatpopsup,andclick"next"severaltimes,acceptingallthedefaultsettings. ChooseanyoftheDownloadsites("ftp.easynet.be",etc.)whenthatwindowcomesuppress"next"andtheCygwininstallershouldstartdownloading. Whenthe"SelectPackages"windowappears,scrolldowntotheheading"Devel"andclickonthe"+"byit.Inthelistofpackagesthatnowdisplays,scrolldownandfindthe"gcccore"packagethisisthecompiler.Clickonceontheword"Skip", anditshouldchangetosomenumberlike"3.4"etc.(theversionnumber),andan"X"willappearnextto"gcccore"andseveralotherrelatedpackagesthatwillnowbedownloaded. 5. Click"next"andthecompileraswellastheCygwintoolsshouldstartdownloadingthiscouldtakeawhile.Whileyou'rewaitingfortheinstallationtofinish,downloadanytexteditordesignedforprogramming.WhileCygwindoesincludesome,you maypreferdoingawebsearchtofindotheralternatives.Whileusingastocktexteditorispossible,itisnotideal. 6. OncetheCygwindownloadsarefinishedandyouhaveclicked"next",etc.tofinishtheinstallation,doubleclicktheCygwinicononyourdesktoptobegintheCygwin"commandprompt".Yourhomedirectorywillautomaticallybesetupinthe Cygwinfolder,whichnowshouldbeat"C:\cygwin"(theCygwinfolderisinsomewayslikeasmallunix/linuxcomputeronyourWindowsmachinenottechnicallyofcourse,butitmaybehelpfultothinkofitthatway). 7. Type"gcc"attheCygwinpromptandpress"enter"if"gcc:noinputfiles"orsomethinglikeitappearsyouhavesucceededandnowhavethegcccompileronyourcomputer(andcongratulationsyouhavealsojustreceivedyourfirsterror message!). Thecurrentstable(usable)versionofGCCis5.1.6publishedon20091002,whichsupportsseveralplatforms.Infact,GCCisnotonlyaCcompiler,butafamilyofcompilersforseverallanguages,suchasC++,Ada,Java,andFortran. Oncegccisinstalled,itcanbecalledwithalistofcsourcefilesthathavebeenwrittenbutnotyetcompiled.eg.thereisamain.cfilethatincludesasomefunctionsdescribedinmyfun.handimplementedinmyfun_a.candmyfun_b.c,thenitisenough towrite
g c c m a i n . cm y f u n _ a . cm y f u n _ b . c
Embeddedsystems
MostCPUsaremicrocontrollersinembeddedsystems,oftenprogrammedinC,butmostofthecompilersmentionedabove(exceptGCC)donotsupportsuchCPUs.Forspecializedcompilersthatdosupportembeddedsystems,seeEmbedded Systems/CProgramming.
AtasteofC
Aswithnearlyeveryotherprogramminglanguagelearningbook,weusethe HelloworldprogramtointroduceyoutoC.
# i n c l u d e< s t d i o . h > i n tm a i n ( v o i d ) { p u t s ( " H e l l o ,w o r l d ! " ) ; r e t u r n0 ; }
en.wikibooks.org/wiki/C_Programming/Print_version
4/118
10/24/13
Thisprogramprints"Hello,world!"andthenexits. EnterthiscodeintoyourtexteditororIDE,andsaveitas"hello.c".
Then,presumingyouareusingGCC,type g c coh e l l oh e l l o . c .Thistellsgcctocompileyourhello.cprogramintoaformthemachinecanexecute.The'ohello'tellsittocallthecompiledprogram'hello'. Ifyouhaveenteredthiscorrectly,youshouldnowseeafilecalledhello.Thisfileisthebinaryversionofyourprogram,andwhenrunshoulddisplay"Hello,world!" Hereisanexampleofhowcompilingandrunninglookswhenusingaterminalonaunixsystem. l s isacommonunixcommandthatwilllistthefilesinthecurrentdirectory,whichinthiscaseisthedirectory p r o g s insidethehomedirectory(represented withthespecialtilde,~,symbol).Afterrunningthe g c c command, l s willlistanewfile, h e l l o ingreen.Greenisthestandardcolorcodingof l s forexecutablefiles.
~ / p r o g s $l s h e l l o . c ~ / p r o g s $g c coh e l l oh e l l o . c ~ / p r o g s $l s h e l l o h e l l o . c ~ / p r o g s $. / h e l l o H e l l o ,w o r l d ! ~ / p r o g s $
Partbypartexplanation
# i n c l u d e< s t d i o . h > tellstheCcompilertofindthestandardheadercalled <stdio.h>andaddittothisprogram.InC,youoftenhavetopullinextraoptionalcomponentswhenyouneedthem. <stdio.h>containsdescriptionsofstandardinput/outputfunctions
whichyoucanusetosendmessagestoauser,ortoreadinputfromauser.
i n tm a i n ( v o i d ) issomethingyou'llfindineveryCprogram.Everyprogramhasa mainfunction.Generally,themainfunctioniswhereaprogrambegins.However,oneCprogramcanbescatteredacrossmultiplefiles,soyouwon'talwaysfindamain
theendofthestring.
r e t u r n0 ; willreturnzero(whichistheintegerreferredtoonline3)totheoperatingsystem.Whenaprogramrunssuccessfullyitsreturnvalueiszero(GCC4complainsifitdoesn'twhencompiling).Anonzerovalueisreturnedtoindicateawarningorerror.
Introexercise
IntroductoryExercises
OnGCC
IfyouareusingaUnix(like)system,suchasGNU/Linux,MacOSX,orSolaris,itwillprobablyhaveGCCinstalled.Typethehelloworldprogramintoafilecalledfirst.candthencompileitwithgcc.Justtype:
g c cf i r s t . c
Thenruntheprogrambytyping:
. / a . o u t
or,IfyouareusingCygwin.
a . e x e
YoushouldnowseeyourveryfirstCprogram.
Therearealotofoptionsyoucanusewiththegcccompiler.Forexample,ifyouwanttheoutputtohaveanameotherthana.out,youcanusetheooption.Thefollowingshowsafewexamples:
c
indicatesthatthecompilerissupposedtogeneratean objectfile,whichcanbelaterlinkedtootherfilestoformafinalprogram.
o
indicatesthatthenextparameteristhenameoftheresultingprogram(orlibrary).Ifthisoptionisnotspecified,thecompiledprogramwill,forhistoricreasons,endupinafilecalled"a.out"or"a.exe"(forcygwinusers).
g 3
en.wikibooks.org/wiki/C_Programming/Print_version
5/118
10/24/13
indicatesthat debugginginformationshouldbeaddedtotheresultsofcompilation.
O 2f f a s t m a t h
indicatesthatthecompilationshouldbeoptimized.
WW a l lf n o c o m m o nW c a s t a l i g nW r e d u n d a n t d e c l sW b a d f u n c t i o n c a s tW w r i t e s t r i n g sW a g g r e g a t e r e t u r nW s t r i c t p r o t o t y p e sW m i s s i n g p r o t o t y p e s
indicatesthatgccshouldwarnaboutmanytypesofsuspiciouscodethatarelikelytobeincorrect.
E
indicatesthatgccshouldonlypreprocessthecodethisisusefulwhenyouarehavingtroubleunderstandingwhatgccisdoingwith#includeand#define,amongotherthings. Alltheoptionsarewelldocumentedinthemanualpage(http://gcc.gnu.org/onlinedocs/gcc4.3.0/gcc/DebuggingOptions.html)forGCC.
theclassicalhelloworldprogram
Thebasichelloworldprogram,fromtheK+RbookonC,isoftenworthmemorising,justforthestructureofthemainfunctionwhichacceptsswitches,justlikegccisaprogramwithamainfunctionthatacceptsswitches.
OnIDEs
IfyouareusingacommercialIDEyoumayhavetoselectconsoleproject,andtocompileyoujustselectbuildfromthemenuorthetoolbar.Theexecutablewillappearinsidetheprojectfolder,butyoushouldhaveamenubuttonsoyoucanjustrunthe executablefromtheIDE. OnecanalsofindopensourceIDE'slikeEclipse,NetbeansorQtCreator.TheprocesswillbethesameasacommercialIDE.
en.wikibooks.org/wiki/C_Programming/Print_version
6/118
10/24/13
BeginningC Preliminaries
BasicConcepts
BeforeonegetstoodeepintolearningCsyntaxandprogrammingconstructs,itisbeneficialtolearnthemeaningofafewkeytermsthatarecentraltoathoroughunderstandingofC.
BlockStructure,Statements,Whitespace,andScope
Nowwe discussthebasicstructureofaCprogram.Ifyou'refamiliarwithPASCAL,youmayhavehearditreferredtoasa blockstructuredlanguage.Cdoesnothavecompleteblockstructure(andyou'llfindoutwhywhenyougooverfunctionsin detail)butitisstillveryimportanttounderstandwhatblocksareandhowtousethem. Sowhatisina block?Generally,ablockconsistsofexecutable statements. Beforewesaywhatablockis,what'sastatement?Onewaytoputitisthatstatementsaretextthecompilerwillattempttoturnintoexecutableinstructions,andthewhitespacethatsurroundsthem.Aneasierwaytoputitisthatstatementsarebitsof codethatdothings,likethis:
i n ti=6 ;/ *t h i sd e c l a r e sav a r i a b l e' i ' ,a n ds e t si tt oe q u a l6* /
Blockscomeinhandywithreadabilityandscope.You'lllearnalittlemoreaboutscopeinasecond. Whitespacereferstothetab,spaceandnewline/EOL(EndOfLine)charactersthatseparatethetextcharactersthatmakeupsourcecodelines.Likemanythingsinlife,it'shardtoappreciatewhitespaceuntilit'sgone.ToaCcompiler,thesourcecode
p r i n t f ( " H e l l ow o r l d " ) ;r e t u r n0 ;
isthesameas
p r i n t f ( " H e l l ow o r l d " ) ; r e t u r n0 ;
whichisthesameas
p r i n t f( " H e l l ow o r l d " );
r e t u r n0 ;
en.wikibooks.org/wiki/C_Programming/Print_version
7/118
10/24/13
Thecompilersimplyskipsoverwhitespace.However,itiscommonpracticetousespaces(andtabs)toorganizesourcecodeforhumanreadability.Youcanuseblockswithoutaconditional,loop,orotherstatementtoorganizeyourcode. InC,mostofthetimewedonotwantotherfunctionsorotherprogrammer'sroutinesaccessingdatathatwearecurrentlymanipulating.Thisiswhyitisimportanttounderstandtheconceptofscope. Scopedescribesthelevelatwhichapieceofdataorafunctionisvisible.TherearetwokindsofscopeinC, local and global .Whenwespeakofsomethingbeing global ,wespeakofsomethingthatcanbeseenormanipulatedfromanywhereinthe program.Whenwespeakofsomethingbeing local ,wespeakofsomethingthatcanbeseenormanipulatedonlywithintheblockitwasdeclared. Let'sshowsomeexamples,togiveabetterpictureoftheideaofscope.
i n ti=5 ;/ *t h i si sa' g l o b a l 'v a r i a b l e ,a n y w h e r ei nt h ep r o g r a mc a na c c e s si t* / / *t h i si saf u n c t i o n ,a l lv a r i a b l e si n s i d eo fi t a r e" l o c a l "t ot h ef u n c t i o n .* / i n tm a i n ( v o i d ) { i n ti=6 ;/ *' i 'n o we q u a l s6* / p r i n t f ( " % d \ n " ,i ) ;/ *p r i n t sa' 6 't ot h es c r e e n ,i n s t e a do ft h eg l o b a lv a r i a b l eo f' i ' ,w h i c hi s5* / r e t u r n0 ; }
Thatshowsadecentexampleoflocalandglobal,butwhataboutdifferentscopes insideoffunctions?(you'lllearnmoreaboutfunctionslater,fornow,justfocusonthe"main"part.)
/ *t h em a i nf u n c t i o n* / i n tm a i n ( v o i d ) { / *t h i si st h eb e g i n n i n go fa' b l o c k ' ,y o ur e a da b o u tt h o s ea b o v e* / i n ti=6 ;/ *t h i si st h ef i r s tv a r i a b l eo ft h i s' b l o c k ' ,' i '* / { / *t h i si san e w' b l o c k ' ,a n db e c a u s ei t ' sad i f f e r e n tb l o c k ,i th a si t so w ns c o p e* / / *t h i si sa l s oav a r i a b l ec a l l e d' i ' ,b u ti nad i f f e r e n t' b l o c k ' , b e c a u s ei t ' si nad i f f e r e n t' b l o c k 't h e nt h eo l d' i ' ,i td o e s n ' ta f f e c tt h eo l do n e !* / i n ti=5 ; p r i n t f ( " % d \ n " ,i ) ;/ *p r i n t sa' 5 'o n t ot h es c r e e n* / } / *n o ww e ' r eb a c ki n t ot h eo l db l o c k* / p r i n t f ( " % d \ n " ,i ) ;/ *p r i n t sa' 6 'o n t ot h es c r e e n* / r e t u r n0 ; }
BasicsofUsingFunctions
Functionsareabigpartofprogramming.Afunctionisaspecialkindofblockthatperformsawelldefinedtask.Ifafunctioniswelldesigned,itcanenableaprogrammertoperformataskwithoutknowinganythingabouthowthefunctionworks.Theact ofrequestingafunctiontoperformitstaskiscalleda functioncall .Manyfunctionsrequireacallertohanditcertainpiecesofdataneededtoperformitstaskthesearecalled arguments.Manyfunctionsalsoreturnavaluetothecallerwhenthey're finishedthisiscalleda returnvalue(thereturnvalueintheaboveprogramis 0). Thethingsyouneedtoknowbeforecallingafunctionare: Whatthefunctiondoes Thedatatype(discussedlater)oftheargumentsandwhattheymean Thedatatypeofthereturnvalueandwhatitmeans Allcodeotherthanglobaldatadefinitionsanddeclarationsneedstobeapartofafunction. Usually,you'refreetocallafunctionwhateveryouwishto.Theonlyrestrictionisthateveryexecutableprogramneedstohaveone,andonlyone, mainfunction,whichiswheretheprogrambeginsexecuting. Wewilldiscussfunctionsinmoredetailinalaterchapter,CProgramming/Proceduresandfunctions.
TheStandardLibrary
In1983,whenCwasintheprocessofbecomingstandardized,theAmericanNationalStandardsInstitute(ANSI)formedacommitteetoestablishastandardspecificationofCknownas"ANSIC".Thatstandardspecificationcreatedabasicsetof functionscommontoeachimplementationofC,whichisreferredtoastheStandardLibrary.TheStandardLibraryprovidesfunctionsfortaskssuchasinput/output,stringmanipulation,mathematics,files,andmemoryallocation.TheStandardLibrary doesnotprovidefunctionsthataredependentonspecifichardwareoroperatingsystems,likegraphics,sound,ornetworking.Inthe"Hello,World",program,aStandardLibraryfunctionisused p r i n t f whichoutputslinesoftexttothestandardoutput stream.
Compiling
HavingcoveredthebasicconceptsofCprogramming,wecannowbrieflydiscusstheprocessof compilation.
Likeanyprogramminglanguage,Cbyitselfiscompletelyincomprehensibletoamicroprocessor.Itspurposeistoprovideanintuitivewayforhumanstoprovideinstructionsthatcanbeeasilyconvertedintomachinecodethat iscomprehensibletoa
en.wikibooks.org/wiki/C_Programming/Print_version
8/118
10/24/13
Likeanyprogramminglanguage,Cbyitselfiscompletelyincomprehensibletoamicroprocessor.Itspurposeistoprovideanintuitivewayforhumanstoprovideinstructionsthatcanbeeasilyconvertedintomachinecodethat iscomprehensibletoa microprocessor.The compileriswhattakesthiscode,andtranslatesitintothemachinecode. Tothosenewtoprogramming,thisseemsfairlysimple.Anaivecompilermightreadineverysourcefile,translateeverythingintomachinecode,andwriteoutanexecutable.Thiscouldwork,buthastwoseriousproblems.First,foralargeproject,the computermaynothaveenoughmemorytoreadallofthesourcecodeatonce.Second,ifyoumakeachangetoasinglesourcefile,youwouldrathernothavetorecompilethe entireapplication. Todealwiththeseproblems,compilersbreaktheirjobdownintostepsforeachsourcefile(each . c file),thecompilerreadsthefile,readsthefilesitreferenceswith # i n c l u d e ,andtranslatesittomachinecode.Theresultofthisisan"objectfile"(. o ).Once everyobjectfileismade,a"linker"collectsalloftheobjectfilesandwritestheactualprogram.Thisway,ifyouchangeonesourcefile,onlythatfileneedstoberecompiledandthentheapplicationneedstoberelinked. Withoutgoingintothepainfuldetails,itcanbebeneficialtohaveasuperficialunderstandingofthecompilationprocess.
Preprocessor
Thepreprocessorprovidestheabilityfortheinclusionofheaderfiles,macroexpansions,conditionalcompilation,andlinecontrol.Manytimesyouwillneedtogivespecialinstructionstoyourcompiler.Thisisdonebyinsertingpreprocessordirectivesinto yourcode.Whenyoubegincompilingyourcode,aspecialprogramcalledthepreprocessorscansthesourcecodeandperformssimplesubstitutionoftokenizedstringsforothersaccordingtopredefinedrules.ThepreprocessorisnotapartoftheC language. InClanguage,allpreprocessordirectivesbeginwiththepoundcharacter(#).YoucanseeonepreprocessordirectiveintheHelloworldprogramintroducedinAtasteofC: Example:
# i n c l u d e< s t d i o . h >
SyntaxChecking
Thisstepensuresthatthecodeisvalidandwillsequenceintoanexecutableprogram.Undermostcompilers,youmaygetmessagesorwarningsindicatingpotentialissueswithyourprogram(suchasastatementalwaysbeingtrueorfalse,etc.) Whenanerrorisdetectedintheprogram,thecompilerwillnormallyreportthefilenameandlinethatispreventingcompilation.
ObjectCode
Thecompilerproducesamachinecodeequivalentofthesourcecodethatcanthenbelinkedintothefinalprogram.Thecodeitselfcan'tbeexecutedyet,asithastocompletethelinkingstage. It'simportanttonoteafterdiscussingthebasicsthatcompilationisa"onewaystreet".Thatis,compilingaCsourcefileintomachinecodeiseasy,but"decompiling"(turningmachinecodeintotheCsourcethatcreatesit)isnot.DecompilersforCdo exist,buttheyrarelycreateusefulcode.
Linking
Linkingcombinestheseparateobjectcodesintoonecompleteprogrambyintegratinglibrariesandthecodeandproducingeitheranexecutableprogramoralibrary.Linkingisperformedbyalinker,whichisoftenpartofacompiler. Commonerrorsduringthisstageareeithermissingfunctions,orduplicatefunctions.
Automation
ForlargeCprojects,manyprogrammerschoosetoautomatecompilation,bothinordertoreduceuserinteractionrequirementsandtospeeduptheprocessbyonlyrecompilingmodifiedfiles. Mostintegrateddevelopmentenvironmentshavesomekindofprojectmanagement,whichmakessuchautomationveryeasy.OnUNIXlikesystems,makeandMakefilesareoftenusedtoaccomplishthesame.
Structureandstyle
CStructureandStyle
ThisisabasicintroductiontogoodcodestyleintheCProgrammingLanguage.Itisdesignedtoprovideinformationonhowtoeffectivelyuseindentation,comments,andotherelementsthatwillmakeyourCcodemorereadable.Itisnotatutorialon actuallyprogramminginC. Asabeginningprogrammer,thepointofcreatingstructureintheprograms'codemightnotbeclear,asthecompilerdoesn'tcareaboutthedifference.However,asprogramsbecomecomplex,chancesarethatwritingtheprogramhasbecomeajoint effort.(Orothersmightwanttoseehowitwasaccomplished.)Therefore,thecodeisnolongerdesignedpurelyforacompilertoread. Inthefollowingsections,wewillattempttoexplaingoodprogrammingpracticesthatwillinturnmakeyourprogramsclearerandmoreeffective.
Introduction
InC,programsarecomposedofstatements.Thesestatementsareterminatedwithasemicolon,andarecollectedinsectionsknownasfunctions.Byconvention,astatementshouldbekeptonitsownline,asshownintheexamplebelow:
# i n c l u d e< s t d i o . h >
en.wikibooks.org/wiki/C_Programming/Print_version
9/118
10/24/13
i n tm a i n ( v o i d ) { p r i n t f ( " H e l l o ,W o r l d ! \ n " ) ; r e t u r n0 ; }
Thefollowingblockofcodeisessentiallythesame:whileitcontainsexactlythesamecode,andwillcompileandexecutewiththesameresult,theremovalofspacingcausesanessentialdifferencemakingithardertoread:
# i n c l u d e< s t d i o . h > i n tm a i n ( v o i d ){ p r i n t f ( " H e l l o ,W o r l d ! \ n " ) ; r e t u r n0 ; }
LineBreaksandIndentation
Theadditionofwhitespaceinsideyourcodeisarguablythemostimportantpartofgoodcodestructure.Effectiveuseofwhitespacecancreateavisualscaleofhowyourcodeflows,whichcanbeveryimportantwhenreturningtoyourcodewhenyou wanttomaintainit.
LineBreaks
Withminimallinebreaks,codeisbarelyreadablebyhumans,andmaybehardtodebugorunderstand:
Ratherthanputtingeverythingononeline,itismuchmorereadabletobreakuplonglinessothateachstatementanddeclarationgoesonitsownline.Afterinsertinglinebreaks,thecodewilllooklikethis:
BlankLines
Blanklinesshouldbeusedtooffsetthemaincomponentsofyourcode.Usethem Afterprecompilerdeclarations. Afternewvariablesaredeclared. Basedonthesetworules,thereshouldnowbetwolinebreaksadded. Afterline1,becauseline1hasapreprocessordirective Afterline4,becauseline4containsavariabledeclaration Thiswillmakethecodemuchmorereadablethanitwasbefore: Thefollowinglinesofcodehavelinebreaksbetweenfunctions,butwithoutindentation.
1 .# i n c l u d e< s t d i o . h > 2 . a i n 3 .i n tm ( v o i d ) 4 .{
en.wikibooks.org/wiki/C_Programming/Print_version
10/118
10/24/13
5 .i n ti = 0 ; 6 . 7 .p r i n t f ( " H e l l o ,W o r l d ! " ) ; i 8 .f o r( = 0 ;i < 1 ;i + + ) 9 .{ 1 0 .p r i n t f ( " \ n " ) ; 1 1 .b r e a k ; 1 2 .} 1 3 .r e t u r n0 ; 1 4 .}
Butthisstillisn'tasreadableasitcanbe.
Indentation
Althoughaddingsimplelinebreaksbetweenkeyblocksofcodecanmakecodeeasiertoread,itprovidesnoinformationabouttheblockstructureoftheprogram.Usingthetabkeycanbeveryhelpfulnow:indentation visuallyseparatespathsofexecutionbymovingtheirstartingpointstoanewcolumnintheline.Thissimplepracticewillmakeitmucheasiertoreadandunderstandcode.Indentationfollowsafairlysimplerule:
Manytexteditors
Comments
Commentsincodecanbeusefulforavarietyofpurposes.Theyprovidetheeasiestwaytosetoffspecificpartsofcode(andtheirpurpose)aswellasprovidingavisual"split"betweenvariouspartsofyourcode.Havinggoodcommentsthroughoutyour codewillmakeitmucheasiertorememberwhatspecificpartsofyourcodedo. CommentsinmodernflavorsofC(andmanyotherlanguages)cancomeintwoforms:
/ / S i n g l eL i n eC o m m e n t s ( a d d e db yC 9 9s t a n d a r d ,f a m o u s l yk n o w na sc + +s t y l eo fc o m m e n t s )
and
/ * M u l t i L i n e C o m m e n t s * /( o n l yf o r mo fc o m m e n t ss u p p o r t e db yC 8 9s t a n d a r d )
NotethatSinglelinecommentsareafairlyrecentadditiontoC,sosomecompilersmaynotsupportthem.ArecentversionofGCCwillhavenoproblemssupportingthem. Thissectionisgoingtofocusonthevarioususesofeachformofcommentary.
SinglelineComments
en.wikibooks.org/wiki/C_Programming/Print_version
11/118
10/24/13
/ /l o o pv a r i a b l e .
/ / E x i t s' f o r 'l o o p .
MultilineComments
Multilinecommentsaremostusefulforlongexplanationsofcode.Theycanbeusedascopyright/licensingnotices,andtheycanalsobeusedtoexplainthepurposeofablockofcode.Thiscanbeusefulfortworeasons: Theymakeyourfunctionseasiertounderstand,andtheymakeiteasiertospoterrorsincode.Ifyouknowwhatablockis supposedtodo,thenitismucheasiertofindthepieceofcodethatisresponsibleifanerroroccurs.
Singlelinecomments
Thissystemallowsforanataglanceexplanationofwhatthefunctionshoulddo.Youcanthengointodetailoverhoweachaspectoftheprogramisachievedlateronintheprogram. Finally,ifyouliketohaveaestheticallypleasingsourcecode,themultilinecommentsystemallowsfortheeasyadditionofcommentboxes.Thesemakethecommentsstandoutmuchmorethantheywouldwithoutotherwise.Theylooklikethis.
/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * T h i si sam u l t il i n ec o m m e n t * T h a ti sn e a r l ys u r r o u n d e db ya * C o o l ,s t a r r yb o r d e r ! * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
Appliedtoouroriginalprogram,wecannowincludeamuchmoredescriptiveandreadablesourcecode:
# i n c l u d e< s t d i o . h > i n tm a i n ( v o i d ) { / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *F u n c t i o n :i n tm a i n ( v o i d ) *I n p u t :n o n e *O u t p u t :R e t u r n s0o ns u c c e s s *P r o c e d u r e :P r i n t s" H e l l o ,W o r l d ! "a n dan e wl i n et os t a n d a r do u t p u tt h e ne x i t s . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
en.wikibooks.org/wiki/C_Programming/Print_version
12/118
10/24/13
i n ti = 0 ; / / T e m p o r a r yv a r i a b l eu s e df o r' f o r 'l o o p .
Thiswillallowanyoutsideusersoftheprogramaneasywaytocomprehendwhatthecodefunctionsareandhowtheyoperate.Italsoinhibitsuncertaintywithotherlikenamedfunctions. Afewprogrammersaddacolumnofstarsontherightsideofablockcomment:
/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * T h i si sam u l t il i n ec o m m e n t * * t h a ti sc o m p l e t e l ys u r r o u n d e db ya* * c o o l ,s t a r r yb o r d e r ! * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
Butmostprogrammersdon'tputanystarsontherightsideofablockcomment.Theyfeelthataligningtherightsideisawasteoftime. CommentswritteninsourcefilescanbeusedfordocumentingsourcecodeautomaticallybyusingpopulartoolslikeDoxygen[4][5]
Links
1. Severalprogrammersrecommend"usespacesforindentation.Donotusetabsinyourcode.Youshouldsetyoureditortoemitspaceswhenyouhitthetabkey."[1](http://googlestyleguide.googlecode.com/svn/trunk/cppguide.xml)[2] (http://www.jwz.org/doc/tabsvsspaces.html)Otherprogrammersdisagree.[3](http://diagrammesmodernes.blogspot.com/2006/04/tabversusspaces.html)[4](http://www.derkarl.org/why_to_tabs.html)Regardlessofwhetheryoupreferspacesor tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5](http://www.oualline.com/vimcook.html#drawing) 3. [http://lxr.linux.no/#linux+v2.6.31/Documentation/CodingStyleLinuxKernelcodingstandard 4. "CodingConventionsforC++andJava"(http://www.macadamian.com/index.php?option=com_content&task=view&id=34&Itemid=37)"alltheblockcommentsillustratedinthisdocumenthavenoprettystarsontherightsideoftheblockcomment. Thisdeliberatechoicewasmadebecausealigningthoseprettystarsisalargewasteoftimeanddiscouragesthemaintenanceofinlinecomments.", 5. wiki:BigBlocksOfAsterisks,"Codecraft"(http://books.google.com/books? id=i4zCzpkrt4sC&pg=PA82&lpg=PA82&dq=programming+comment+block+waste+time+lining+up&source=bl&ots=TUpTMIHBnh&sig=NeZm23WPmvnw2aKMnIRUeQoHmJg&hl=en&ei=pri3SevGIYGyNMn9jd4K&sa=X&oi=book_result&resnum=8&ct=result) byPeteGoodliffepage82,Falvotech"CProgrammingStyleGuide"(http://www.falvotech.com/content/publications/conventions/c/),FedoraDirectoryServerCodingStyle(http://directory.fedoraproject.org/wiki/Coding_Style) Aladdin'sCcodingguidelines(http://www.cs.wisc.edu/~ghost/doc/AFPL/6.01/Cstyle.htm)AmoredefinitiveCcodingguideline. C/C++ProgrammingStyles(http://www.mycplus.com/c.asp?ID=12)GNUCodingstyles&LinuxKernelCodingstyle CProgrammingTutorial(http://www.studiesinn.com/learn/ProgrammingLanguages/CLanguage.html)CProgrammingTutorial
Errorhandling
Cdoesnotprovidedirectsupportforerrorhandling(alsoknownasexceptionhandling).Byconvention,theprogrammerisexpectedtopreventerrorsfromoccurringinthefirstplace,andtestreturnvaluesfromfunctions.Forexample,1andNULLare usedinseveralfunctionssuchassocket()(Unixsocketprogramming)ormalloc()respectivelytoindicateproblemsthattheprogrammershouldbeawareabout.Inaworstcasescenariowherethereisanunavoidableerrorandnowaytorecoverfromit,a Cprogrammerusuallytriestologtheerrorand"gracefully"terminatetheprogram. Thereisanexternalvariablecalled"errno",accessiblebytheprogramsafterincluding<errno.h>thatfilecomesfromthedefinitionofthepossibleerrorsthatcanoccurinsomeOperatingSystems(e.g.Linuxinthiscase,thedefinitionisininclude/asm generic/errno.h)whenprogramsaskforresources.Suchvariableindexeserrordescriptionsaccessiblebythefunction'strerror(errno)'. Thefollowingcodeteststhereturnvaluefromthelibraryfunctionmalloctoseeifdynamicmemoryallocationcompletedproperly:
# i n c l u d e< s t d i o . h > # i n c l u d e< e r r n o . h > # i n c l u d e< s t d l i b . h > # i n c l u d e< s t r i n g . h > e x t e r ni n te r r n o ; i n tm a i n (v o i d) { / *p o i n t e rt oc h a r ,r e q u e s t i n gd y n a m i ca l l o c a t i o no f2 , 0 0 0 , 0 0 0 , 0 0 0 *s t o r a g ee l e m e n t s( d e c l a r e da sa ni n t e g e rc o n s t a n to ft y p e *u n s i g n e dl o n gi n t ) .( I fy o u rs y s t e mh a sl e s st h a n2 G Bo fm e m o r y *a v a i l a b l e ,t h e nt h i sc a l lt om a l l o cw i l lf a i l ) * / c h a r* p t r=m a l l o c (2 0 0 0 0 0 0 0 0 0 U L) ; / *f p r i n t f* / / *e r r n o* / / *m a l l o c ,f r e e ,e x i t* / / *s t r e r r o r* /
en.wikibooks.org/wiki/C_Programming/Print_version
13/118
10/24/13
i f(p t r= =N U L L) { p u t s ( " m a l l o cf a i l e d " ) ; p u t s ( s t r e r r o r ( e r r n o ) ) ; } e l s e { / *t h er e s to ft h ec o d eh e r e a f t e rc a na s s u m et h a t2 , 0 0 0 , 0 0 0 , 0 0 0 *c h a r sw e r es u c c e s s f u l l ya l l o c a t e d . . . * / f r e e (p t r) ; } e x i t ( E X I T _ S U C C E S S ) ;/ *e x i t i n gp r o g r a m* / }
Thecodesnippetaboveshowstheuseofthereturnvalueofthelibraryfunctionmalloctocheckforerrors.Manylibraryfunctionshavereturnvaluesthatflagerrors,andthusshouldbecheckedbytheastuteprogrammer.Inthesnippetabove,aNULL pointerreturnedfrommallocsignalsanerrorinallocation,sotheprogramexits.Inmorecomplicatedimplementations,theprogrammighttrytohandletheerrorandtrytorecoverfromthefailedmemoryallocation.
Preventingdividebyzeroerrors
AcommonpitfallmadebyCprogrammersisnotcheckingifadivisoriszerobeforeadivisioncommand.Thefollowingcodewillproducearuntimeerrorandinmostcases,exit.
i n td i v i d e n d=5 0 ; i n td i v i s o r=0 ; i n tq u o t i e n t ; q u o t i e n t=( d i v i d e n d / d i v i s o r ) ;/ *T h i sw i l lp r o d u c ear u n t i m ee r r o r !* /
Forreasonsbeyondthescopeofthisdocument,youmustcheckormakesurethatadivisorisneverzero.Alternatively,for*nixprocesses,youcanstoptheOSfromterminatingyourprocessbyblockingtheSIGFPEsignal. Thecodebelowfixesthisbycheckingifthedivisoriszerobeforedividing.
# i n c l u d e< s t d i o . h >/ *f o rf p r i n t fa n ds t d e r r* / # i n c l u d e< s t d l i b . h >/ *f o re x i t* / i n tm a i n (v o i d) { i n td i v i d e n d=5 0 ; i n td i v i s o r=0 ; i n tq u o t i e n t ; i f( d i v i s o r= =0 ){ / *E x a m p l eh a n d l i n go ft h i se r r o r .W r i t i n gam e s s a g et os t d e r r ,a n d *e x i t i n gw i t hf a i l u r e . * / f p r i n t f ( s t d e r r ," D i v i s i o nb yz e r o !A b o r t i n g . . . \ n " ) ; e x i t ( E X I T _ F A I L U R E ) ;/ *i n d i c a t ef a i l u r e . * / } q u o t i e n t=d i v i d e n d/d i v i s o r ; e x i t ( E X I T _ S U C C E S S ) ;/ *i n d i c a t es u c c e s s . * / }
Signals
Insomecases,theenvironmentmayrespondtoaprogrammingerrorinCbyraisingasignal.Signalsareeventsraisedbythehostenvironmentoroperatingsystemtoindicatethataspecificerrororcriticaleventhasoccurred(e.g.adivisionbyzero, interrupt,andsoon.)However,thesesignalsarenotmeanttobeusedasameansoferrorcatchingtheyusuallyindicateacriticaleventthatwillinterferewithnormalprogramflow. Tohandlesignals,aprogramneedstousethe s i g n a l . h headerfile.Asignalhandlerwillneedtobedefined,andthesignal()functionisthencalledtoallowthegivensignaltobehandled.Somesignalsthatareraisedtoanexceptionwithinyourcode(e.g. adivisionbyzero)areunlikelytoallowyourprogramtorecover.Thesesignalhandlerswillberequiredtoinsteadensurethatsomeresourcesareproperlycleanedupbeforetheprogramterminates. Thisexamplecreatesasignalhandlerandraisesthesignal:
# i n c l u d e< s i g n a l . h > # i n c l u d e< s t d i o . h > # i n c l u d e< s t d l i b . h > s t a t i cv o i dc a t c h _ f u n c t i o n ( i n ts i g n a l ){ p u t s ( " I n t e r a c t i v ea t t e n t i o ns i g n a lc a u g h t . " ) ; } i n tm a i n ( v o i d ){ i f( s i g n a l ( S I G I N T ,c a t c h _ f u n c t i o n )= =S I G _ E R R ){ f p u t s ( " A ne r r o ro c c u r r e dw h i l es e t t i n gas i g n a lh a n d l e r . \ n " ,s t d e r r ) ; r e t u r nE X I T _ F A I L U R E ; } p u t s ( " R a i s i n gt h ei n t e r a c t i v ea t t e n t i o ns i g n a l . " ) ; i f( r a i s e ( S I G I N T )! =0 ){ f p u t s ( " E r r o rr a i s i n gt h es i g n a l . \ n " ,s t d e r r ) ;
en.wikibooks.org/wiki/C_Programming/Print_version
14/118
10/24/13
r e t u r nE X I T _ F A I L U R E ; } p u t s ( " E x i t i n g . " ) ; r e t u r n0 ; }
setjmp
Thesetjmpfunctioncanbeusedtoemulatetheexceptionhandlingfeatureofotherprogramminglanguages.Thefirstcalltosetjmpprovidesareferencepointtoreturningtoagivenfunction,andisvalidaslongasthefunctioncontainingsetjmp()doesn't returnorexit.Acalltolongjmpcausestheexecutiontoreturntothepointoftheassociatedsetjmpcall.
# i n c l u d e< s t d i o . h > # i n c l u d e< s e t j m p . h > j m p _ b u ft e s t 1 ; v o i dt r y j u m p ( ) { l o n g j m p ( t e s t 1 ,3 ) ; } i n tm a i n( v o i d ) { i f( s e t j m p ( t e s t 1 ) = = 0 ){ p r i n t f( " s e t j m p ( )r e t u r n e d0 . " ) ; t r y j u m p ( ) ; }e l s e{ p r i n t f( " s e t j m pr e t u r n e df r o mal o n g j m pf u n c t i o nc a l l . " ) ; } }
Thevaluesofnonvolatilevariablesmaybecorruptedwhensetjmpreturnsfromalongjmpcall. Whilesetjmp()andlongjmp()maybeusedforerrorhandling,itisgenerallypreferredtousethereturnvalueofafunctiontoindicateanerror,ifpossible.
Variables
Likemostprogramminglanguages,Cisabletouseandprocessnamedvariablesandtheircontents. Variablesaresimplynamesusedtorefertosomelocationinmemoryalocationthatholdsavaluewithwhichweareworking. Itmayhelptothinkofvariablesasaplaceholderforavalue.Youcanthinkofavariableasbeingequivalenttoitsassignedvalue.So,ifyouhaveavariable ithatis initialized(setequal)to4,thenitfollowsthat i+1willequal 5. SinceCisarelativelylowlevelprogramminglanguage,beforeaCprogramcanutilizememorytostoreavariableitmustclaimthememoryneededtostorethevaluesforavariable.Thisisdoneby declaringvariables.Declaringvariablesisthewayin whichaCprogramshowsthenumberofvariablesitneeds,whattheyaregoingtobenamed,andhowmuchmemorytheywillneed. WithintheCprogramminglanguage,whenmanagingandworkingwithvariables,itisimportanttoknowthe typeofvariablesandthe sizeofthesetypes.SinceCisafairlylowlevelprogramminglanguage,theseaspectsofitsworkingcanbehardware specificthatis,howthelanguageismadetoworkononetypeofmachinecanbedifferentfromhowitismadetoworkonanother. AllvariablesinCare typed.Thatis,everyvariabledeclaredmustbeassignedasacertaintypeofvariable.
Declaring,Initializing,andAssigningVariables
Hereisanexampleofdeclaringaninteger,whichwe'vecalled s o m e _ n u m b e r .(Notethesemicolonattheendofthelinethatishowyourcompilerseparatesoneprogram statement fromanother.)
i n ts o m e _ n u m b e r ;
Wecanalsodeclare andassignsomecontenttoavariableatthesametime.
i n ts o m e _ n u m b e r = 3 ;
en.wikibooks.org/wiki/C_Programming/Print_version
15/118
10/24/13
Afterdeclaringvariables,youcanassignavaluetoavariablelateronusingastatementlikethis:
s o m e _ n u m b e r = 3 ;
Youcanalsoassignavariablethevalueofanothervariable,likeso:
a n u m b e r=a n o t h e r n u m b e r ;
Orassignmultiplevariablesthesamevaluewithonestatement:
a n u m b e r=a n o t h e r n u m b e r=y e t a n o t h e r n u m b e r=3 ;
NamingVariables
VariablenamesinCaremadeupofletters(upperandlowercase)anddigits.Theunderscorecharacter("_")isalsopermitted.Namesmustnotbeginwithadigit.Unlikesomelanguages(suchasPerlandsomeBASICdialects),Cdoesnotuseany specialprefixcharactersonvariablenames. Someexamplesofvalid(butnotverydescriptive)Cvariablenames:
f o o B a r B A Z f o o _ b a r _ f o o 4 2 _ Q u U x
SomeexamplesofinvalidCvariablenames:
2 f o o m yf o o $ f o o w h i l e ( m u s tn o tb e g i nw i t had i g i t ) ( s p a c e sn o ta l l o w e di nn a m e s ) ( $n o ta l l o w e d-o n l yl e t t e r s ,d i g i t s ,a n d_ ) ( l a n g u a g ek e y w o r d sc a n n o tb eu s e da sn a m e s )
Literals
Anytimewithinaprograminwhichyouspecifyavalueexplicitlyinsteadofreferringtoavariableorsomeotherformofdata,thatvalueisreferredtoasa literal .Intheinitializationexampleabove,3isaliteral.Literalscaneithertakeaformdefinedby theirtype(moreonthatsoon),oronecanusehexadecimal(hex)notationtodirectlyinsertdataintoavariableregardlessofitstype. [citationneeded]Hexnumbersarealwaysprecededwith 0x.Fornow,though,youprobablyshouldn'tbetooconcernedwith hex.
TheFourBasicDataTypes
InStandardCtherearefourbasicdatatypes.Theyare i n t , c h a r , f l o a t ,and d o u b l e . Wewillbrieflydescribethemhere,thengointomoredetailinCProgramming/Types.
Thei n t type
The i n t typestoresintegersintheformof"wholenumbers".Anintegeristypicallythesizeofonemachineword,whichonmostmodernhomePCsis32bits(4octets).Examplesofliteralsarewholenumbers(integers)suchas1,2,3,10,100...When i n t is32bits(4octets),itcanstoreanywholenumber(integer)between2147483648and2147483647.A32bitword(number)hasthepossibilityofrepresentinganyonenumberoutof4294967296possibilities(2tothepowerof32). Ifyouwanttodeclareanewintvariable,usethe i n t keyword.Forexample:
i n tn u m b e r O f S t u d e n t s ,i ,j = 5 ;
en.wikibooks.org/wiki/C_Programming/Print_version
16/118
10/24/13
Inthisdeclarationwedeclare3variables,numberOfStudents,iandj,jhereisassignedtheliteral5.
Thec h a r type
The c h a r typeiscapableofholdinganymemberoftheexecutioncharacterset.Itstoresthesamekindofdataasan i n t (i.e.integers),buttypicallyhasasizeofonebyte.Thesizeofabyteisspecifiedbythemacro C H A R _ B I T whichspecifiesthenumberof bitsinachar(byte).InstandardCitnevercanbelessthan8bits.Avariableoftype c h a r ismostoftenusedtostorecharacterdata,henceitsname.MostimplementationsusetheASCIIcharactersetastheexecutioncharacterset,butit'sbestnotto knoworcareaboutthatunlesstheactualvaluesareimportant. Examplesofcharacterliteralsare'a','b','1',etc.,aswellassomespecialcharacterssuchas'\ 0 '(thenullcharacter)and'\ n '(newline,recall"Hello,World").Notethatthe c h a r valuemustbeenclosedwithinsinglequotations. Whenweinitializeacharactervariable,wecandoittwoways.Oneispreferred,theotherwayis badprogrammingpractice. Thefirstwayistowrite
c h a rl e t t e r 1=' a ' ;
Thisisconsideredbysometobeextremely badpractice,ifweareusingittostoreacharacter,notasmallnumber,inthatifsomeonereadsyourcode,mostreadersareforcedtolookupwhatcharactercorrespondswiththenumber97intheencoding scheme.Intheend, l e t t e r 1 and l e t t e r 2 storeboththesamethingtheletter'a',butthefirstmethodisclearer,easiertodebug,andmuchmorestraightforward. Oneimportantthingtomentionisthatcharactersfornumeralsarerepresenteddifferentlyfromtheircorrespondingnumber,i.e.'1'isnotequalto1.Inshort,anysingleentrythatisenclosedwithin'singlequotes'. Thereisonemorekindofliteralthatneedstobeexplainedinconnectionwithchars:the stringliteral .Astringisaseriesofcharacters,usuallyintendedtobedisplayed.Theyaresurroundedbydoublequotations("",not'').Anexampleofastringliteral isthe"Hello,World!\n"inthe"Hello,World"example. Thestringliteralisassignedtoacharacter array,arraysaredescribedlater.Example:
c o n s tc h a rM Y _ C O N S T A N T _ P E D A N T I C _ I T C H [ ]=" l e a r nt h eu s a g ec o n t e x t . \ n " ; p r i n t f ( " S q u a r eb r a c k e t sa f t e rav a r i a b l en a m em e a n si ti sap o i n t e rt oas t r i n go fm e m o r yb l o c k st h es i z eo ft h et y p eo ft h ea r r a ye l e m e n t . \ n " ) ;
Thef l o a t type
f l o a t isshortfor floatingpoint.Itstoresrealnumbersalso,butisonlyonemachinewordinsize.Therefore,itisusedwhenlessprecisionthanadoubleprovidesisrequired. f l o a t literalsmustbesuffixedwithForf,otherwisetheywillbeinterpretedas
Thed o u b l e type
The d o u b l e and f l o a t typesareverysimilar.The f l o a t typeallowsyoutostoresingleprecisionfloatingpointnumbers,whilethe d o u b l e keywordallowsyoutostoredoubleprecisionfloatingpointnumbersrealnumbers,inotherwords,bothintegerandnon integervalues.Itssizeistypicallytwomachinewords,or8bytesonmostmachines.Examplesof d o u b l e literalsare3.1415926535897932,4.0,6.022e+23(scientificnotation).Ifyouuse4insteadof4.0,the4willbeinterpretedasan i n t . Thedistinctionbetweenfloatsanddoubleswasmadebecauseofthedifferingsizesofthetwotypes.WhenCwasfirstused,spacewasataminimumandsothejudicioususeofafloatinsteadofadoublesavedsomememory.Nowadays,withmemory morefreelyavailable,youdonotreallyneedtoconservememorylikethisitmaybebettertousedoublesconsistently.Indeed,someCimplementationsusedoublesinsteadoffloatswhenyoudeclareafloatvariable. Ifyouwanttouseadoublevariable,usethe d o u b l e keyword.
s i z e o f
Ifyouhaveanydoubtsastotheamountofmemoryactuallyusedbyanyvariable(andthisgoesfortypeswe'lldiscusslater,also),youcanusethe s i z e o f operatortofindoutforsure.(Forcompleteness,itisimportanttomentionthat s i z e o f isaunary operator,notafunction.)Itssyntaxis:
s i z e o fo b j e c t s i z e o f ( t y p e )
en.wikibooks.org/wiki/C_Programming/Print_version
17/118
10/24/13
s i z e o f ( c h a r )
alwaysreturns1.
Datatypemodifiers
Onecanalterthedatastorageofanydatatypebyprecedingitwithcertainmodifiers.
l o n g and s h o r t aremodifiersthatmakeitpossibleforadatatypetouseeithermoreorlessmemory.The i n t keywordneednotfollowthe s h o r t and l o n g keywords.Thisismostcommonlythecase.A s h o r t canbeusedwherethevaluesfallwithinalesser
rangethanthatofan i n t ,typically32768to32767.A l o n g canbeusedtocontainanextendedrangeofvalues.Itisnotguaranteedthata s h o r t useslessmemorythanan i n t ,norisitguaranteedthata l o n g takesupmorememorythanan i n t .Itisonly guaranteedthatsizeof(short)<=sizeof(int)<=sizeof(long).Typicallya s h o r t is2bytes,an i n t is4bytes,anda l o n g either4or8bytes.ModernCcompilersalsoprovide l o n gl o n g whichistypicallyan8byteinteger. Inallofthetypesdescribedabove,onebitisusedtoindicatethesign(positiveornegative)ofavalue.Ifyoudecidethatavariablewillneverholdanegativevalue,youmayusethe u n s i g n e d modifiertousethatonebitforstoringotherdata,effectively doublingtherangeofvalueswhilemandatingthatthosevaluesbepositive.The u n s i g n e d specifieralsomaybeusedwithoutatrailing i n t ,inwhichcasethesizedefaultstothatofan i n t .Thereisalsoa s i g n e d modifierwhichistheopposite,butitisnot necessary,exceptforcertainusesof c h a r ,andseldomusedsincealltypes(except c h a r )aresignedbydefault. Touseamodifier,justdeclareavariablewiththedatatypeandrelevantmodifiers:
u n s i g n e ds h o r ti n tu s i ; / *f u l l yq u a l i f i e d-u n s i g n e ds h o r ti n t* / s h o r ts i ; / *s h o r ti n t* / u n s i g n e dl o n gu l i ; / *u n s i g n e dl o n gi n t* /
c o n s t qualifier
Whenthe c o n s t qualifierisused,thedeclaredvariablemustbeinitializedatdeclaration.Itisthennotallowedtobechanged. Whiletheideaofavariablethatneverchangesmaynotseemuseful,therearegoodreasonstouse c o n s t .Foronething,manycompilerscanperformsomesmalloptimizationsondatawhenitknowsthatdatawillneverchange.Forexample,ifyouneed thevalueofinyourcalculations,youcandeclareaconstvariableof p i ,soaprogramoranotherfunctionwrittenbysomeoneelsecannotchangethevalueof p i . NotethataStandardconformingcompilermustissueawarningifanattemptismadetochangea c o n s t variablebutafterdoingsothecompilerisfreetoignorethe c o n s t qualifier.
Magicnumbers
WhenyouwriteCprograms,youmaybetemptedtowritecodethatwilldependoncertainnumbers.Forexample,youmaybewritingaprogramforagrocerystore.Thiscomplexprogramhasthousandsuponthousandsoflinesofcode.Theprogrammer decidestorepresentthecostofacanofcorn,currently99cents,asaliteralthroughoutthecode.Now,assumethecostofacanofcornchangesto89cents.Theprogrammermustnowgoinandmanuallychangeeachentryof99centsto89.Whilethis isnotthatbigofaproblem,consideringthe"globalfindreplace"functionofmanytexteditors,consideranotherproblem:thecostofacanofgreenbeansisalsoinitially99cents.Toreliablychangetheprice,youhavetolookateveryoccurrenceofthe number99. Cpossessescertainfunctionalitytoavoidthis.Thisfunctionalityisapproximatelyequivalent,thoughonemethodcanbeusefulinonecircumstance,overanother.
Usingthec o n s t keyword
The c o n s t keywordhelpseradicate magicnumbers.Bydeclaringavariable c o n s tc o r n atthebeginningofablock,aprogrammercansimplychangethatconstandnothavetoworryaboutsettingthevalueelsewhere. Thereisalsoanothermethodforavoidingmagicnumbers.Itismuchmoreflexiblethan c o n s t ,andalsomuchmoreproblematicinmanyways.Italsoinvolvesthepreprocessor,asopposedtothecompiler.Behold...
# d e f i n e
whenyouwantto,forexample,printthepriceofcorn,youusetheword P R I C E _ O F _ C O R N insteadofthenumber0.99thepreprocessorwillreplaceallinstancesof P R I C E _ O F _ C O R N with0.99,whichthecompilerwillinterpretastheliteral d o u b l e 0.99.The preprocessorperformssubstitution,thatis, P R I C E _ O F _ C O R N isreplacedby0.99sothismeansthereisnoneedforasemicolon. Itisimportanttonotethat # d e f i n e hasbasicallythesamefunctionalityasthe"findandreplace"functioninalotoftexteditors/wordprocessors. Forsomepurposes, # d e f i n e canbeharmfullyused,anditisusuallypreferabletouse c o n s t if # d e f i n e isunnecessary.Itispossible,forinstance,to # d e f i n e ,say,amacro D O G asthenumber3,butifyoutrytoprintthemacro,thinkingthat D O G representsastring thatyoucanshowonthescreen,theprogramwillhaveanerror. # d e f i n e alsohasnoregardfortype.Itdisregardsthestructureofyourprogram,replacingthetext everywhere(ineffect,disregardingscope),whichcouldbeadvantageousinsome circumstances,butcanbethesourceofproblematicbugs. Youwillseefurtherinstancesofthe # d e f i n e directivelaterinthetext.Itisgoodconventiontowrite # d e f i n e dwordsinallcapitals,soaprogrammerwillknowthatthisisnotavariablethatyouhavedeclaredbuta # d e f i n e dmacro.Itisnotnecessarytoenda preprocessordirectivesuchas # d e f i n e withasemicoloninfact,somecompilersmaywarnyouaboutunnecessarytokensinyourcodeifyoudo.
Scope
en.wikibooks.org/wiki/C_Programming/Print_version 18/118
10/24/13
OtherModifiers
Includedhere,forcompleteness,aremoreofthemodifiersthatstandardCprovides.Forthebeginningprogrammer, staticand externmaybeuseful. volatileismoreofinteresttoadvancedprogrammers. registerand autoarelargelydeprecatedandare generallynotofinteresttoeitherbeginningoradvancedprogrammers.
static
s t a t i c issometimesausefulkeyword.Itisacommonmisbeliefthattheonlypurposeistomakeavariablestayinmemory.
Featuresof s t a t i c variables:
1 .K e y w o r du s e d -s t a t i c 2 .S t o r a g e -M e m o r y 3 .D e f a u l tv a l u e -Z e r o 4 .S c o p e -L o c a lt ot h eb l o c ki nw h i c hi ti sd e c l a r e d 5 .L i f e t i m e -V a l u ep e r s i s t sb e t w e e nd i f f e r e n tf u n c t i o nc a l l s 6 .K e y w o r do p t i o n a l i t y-M a n d a t o r yt ou s et h ek e y w o r d
en.wikibooks.org/wiki/C_Programming/Print_version
19/118
10/24/13
extern
volatile
v o l a t i l e isaspecialtypeofmodifierwhichinformsthecompilerthatthevalueofthevariablemaybechangedbyexternalentitiesotherthantheprogramitself.Thisisnecessaryforcertainprogramscompiledwithoptimizationsifavariablewerenot
auto
a u t o isamodifierwhichspecifiesan"automatic"variablethatisautomaticallycreatedwheninscopeanddestroyedwhenoutofscope.Ifyouthinkthissoundslikeprettymuchwhatyou'vebeendoingallalongwhenyoudeclareavariable,you'reright:all
register
r e g i s t e r isahinttothecompilertoattempttooptimizethestorageofthegivenvariablebystoringitinaregisterofthecomputer'sCPUwhentheprogramisrun.Mostoptimizingcompilersdothisanyway,souseofthiskeywordisoftenunnecessary.In
Concepts
Variables Types DataStructures Arrays
Inthissection
Cvariables Ctypes Carrays
SimpleInputandOutput
Whenyoutaketimetoconsiderit,acomputerwouldbeprettyuselesswithoutsomewaytotalktothepeoplewhouseit.Justlikeweneedinformationinordertoaccomplishtasks,sodocomputers.Andjustaswesupplyinformationtootherssothat theycandotasks,sodocomputers.
en.wikibooks.org/wiki/C_Programming/Print_version
20/118
10/24/13
Outputusingprintf()
Recallfromthebeginningofthistextthedemonstrationprogramduplicatedbelow:
# i n c l u d e< s t d i o . h > i n tm a i n ( v o i d ) { p r i n t f ( " H e l l o ,w o r l d ! \ n " ) ; r e t u r n0 ; }
Ifyoucompileandrunthisprogram,youwillseethesentencebelowshowuponyourscreen:
H e l l o ,w o r l d !
Thisamazingaccomplishmentwasachievedbyusingthe function p r i n t f ( ) .Afunctionislikea"blackbox"thatdoessomethingforyouwithoutexposingtheinternalsinside.WecanwritefunctionsourselvesinC,butwewillcoverthatlater. Youhaveseenthattouse p r i n t f ( ) oneputstext,surroundedbyquotes,inbetweentheparentheses.Wecallthetextsurroundedbyquotesa literalstring(orjusta string),andwecallthatstringan argument toprintf. Asanoteofexplanation,itissometimesconvenienttoincludetheopenandclosingparenthesesafterafunctionnametoremindusthatitis,indeed,afunction.Howeverusuallywhenthenameofthefunctionwearetalkingaboutisunderstood,itisnot necessary. Asyoucanseeintheexampleabove,using p r i n t f ( ) canbeassimpleastypinginsometext,surroundedbydoublequotes(notethatthesearedoublequotesandnottwosinglequotes).So,forexample,youcanprintanystringbyplacingitasan argumenttothe p r i n t f ( ) function:
p r i n t f ( " T h i ss e n t e n c ew i l lp r i n to u te x a c t l ya sy o us e ei t . . . " ) ;
Andonceitiscontainedinaproper m a i n ( ) function,itwillshow:
T h i ss e n t e n c ew i l lp r i n to u te x a c t l ya sy o us e ei t . . .
Printingnumbersandescapesequences
Placeholdercodes The p r i n t f functionisapowerfulfunction,andisprobablythemostusedfunctioninCprograms. Forexample,letuslookataproblem.Saywedon'tknowwhat19+31is.Let'suseCtogettheanswer. Westartwriting
# i n c l u d e" s t d i o . h "/ /t h i si si m p o r t a n t ,s i n c ep r i n t f / /c a n ' tb eu s e dw i t h o u tt h i sl i n e
i n tm a i n ( v o i d ) {
en.wikibooks.org/wiki/C_Programming/Print_version
21/118
10/24/13
p r i n t f ( " 1 9 + 3 1i s " ) ;
Theplaceholder%dliterally"holdstheplace"fortheactualnumberthatistheresultofadding19to31. Theseplaceholdersarecalled formatspecifiers.Manyotherformatspecifiersworkwith p r i n t f .Ifwehaveafloatingpointnumber,wecanuse % f toprintoutafloatingpointnumber,decimalpointandall.Otherformatspecifiersare: %dint(sameas%i) %ldlongint(sameas%li) %ffloat %lfdouble %cchar %sstring %xhexadecimal Tabsandnewlines Whatif,wewanttoachievesomeoutputthatwilllooklike:
1 9 0 5 3 1 2+ -
p r i n t f willnotputlinebreaksinattheendofeachstatement:wemustdothisourselves.Buthow?
ortobeabitmoreclear,wecanbreakthislongprintfstatementoverseverallines.Soourprogramwillbe
# i n c l u d e< s t d i o . h > i n tm a i n ( v o i d ) { p r i n t f ( "1 9 0 5 \ n " ) ; p r i n t f ( " 3 1 2+ \ n " ) ; p r i n t f ( " \ n " ) ; p r i n t f ( " % d " ,1 9 0 5 + 3 1 2 ) ; r e t u r n0 ; }
Otheroutputmethods
puts()
Theputs()functionisaverysimplewaytosendastringtothescreenwhenyouhavenoplaceholderstobeconcernedabout.Itworksverymuchliketheprintf()functionwesawinthe"Hello,World!"example:
p u t s ( " P r i n tt h i ss t r i n g . " ) ;
willprinttothescreen:
P r i n tt h i ss t r i n g .
en.wikibooks.org/wiki/C_Programming/Print_version
22/118
10/24/13
followedbythenewlinecharacter(asdiscussedabove).(The p u t s functionappendsanewlinecharactertoitsoutput.)
# i n c l u d e < s t d i o . h > f ( i n ti , i n tj , i n tk ) { p r i n t f ( " % d % d % d " , i , j , k ) ; } m a i n ( ) { i n tx = 1 , y = 2 , z = 3 ; f ( x + y , y = x + z , z = x + y ) ; }
Inputusingscanf()
Thescanf()functionistheinputmethodequivalenttotheprintf()outputfunctionsimpleyetpowerful.Initssimplestinvocation,thescanf formatstringholdsasingle placeholderrepresentingthetypeofvaluethatwillbeenteredbytheuser.These placeholdersareexactlythesameastheprintf()function%dforints,%fforfloats,and%lffordoubles. Thereis,however,onevariationtoscanf()ascomparedtoprintf().Thescanf()functionrequiresthememoryaddressofthevariabletowhichyouwanttosavetheinputvalue.While pointersarepossiblehere,thisisaconceptthatwon'tbeapproached untillaterinthetext.Instead,thesimpletechniqueistousethe addressof operator, &.Fornowitmaybebesttoconsiderthis"magic"beforewediscusspointers. Atypicalapplicationmightbelikethis:
# i n c l u d e" s t d i o . h " i n tm a i n ( v o i d ) { i n ta ; p r i n t f ( " P l e a s ei n p u ta ni n t e g e rv a l u e :" ) ; s c a n f ( " % d " ,& a ) ; p r i n t f ( " Y o ue n t e r e d :% d \ n " ,a ) ; r e t u r n0 ; }
Thecorrectusagewouldbe:
s c a n f ( " % s " ,a ) ;
Links
Backtocontents:BeginningC
Simplemath
OperatorsandAssignments
Chasawiderangeofoperatorsthatmakesimplematheasytohandle.Thelistofoperatorsgroupedintoprecedencelevelsisasfollows:
Primaryexpressions
Anidentifierisaprimaryexpression,providedthatithasbeendeclaredasdesignatinganobject(inwhichcaseitisanlvalue[avaluethatcanbeusedastheleftsideofanassignmentexpression])orafunction(inwhichcaseitisafunctiondesignator). Aconstantisaprimaryexpression.Itstypedependsonitsformandvalue.
en.wikibooks.org/wiki/C_Programming/Print_version
23/118
10/24/13
Astringliteralisaprimaryexpression.
Aparenthesizedexpressionisaprimaryexpression.Itstypeandvaluearethoseoftheunparenthesizedexpression.
Postfixoperators
First,aprimaryexpressionisalsoapostfixexpression.Thefollowingexpressionsarealsopostfixexpressions: Apostfixexpressionfollowedbyaleftsquarebracket([ ),anexpression,andarightsquarebracket(] )constitutesaninvocationofthearraysubscriptoperator.Oneoftheexpressionsshallhavetype"pointertoobject type"andtheothershallhavean integertypetheresulttypeis type.Successivearraysubscriptoperatorsdesignateanelementofamultidimensionalarray. Apostfixexpressionfollowedbyparenthesesoranoptionalparenthesizedargumentlistindicatesaninvocationofthefunctioncalloperator. Apostfixexpressionfollowedbyadot(. )followedbyanidentifierselectsamemberfromastructureorunionapostfixexpressionfollowedbyanarrow(> )followedbyanidentifierselectsamemberfromastructureorunionwhoispointedtobythe pointeronthelefthandsideoftheexpression. Apostfixexpressionfollowedbytheincrementordecrementoperators(+ + or )indicatesthatthevariableistobeincrementedordecrementedasasideeffect.Thevalueoftheexpressionisthevalueofthepostfixexpression beforetheincrementor decrement.
Unaryexpressions
First,aunaryexpressionisapostfixexpression.Thefollowingexpressionsareallpostfixexpressions: Theincrementordecrementoperatorsfollowedbyaunaryexpressionisaunaryexpression.Thevalueoftheexpressionisthevalueoftheunaryexpression aftertheincrementordecrement. Thefollowingoperatorsfollowedbyacastexpressionareunaryexpressions:
O p e r a t o r = = = = = = = = & * + ! ~ M e a n i n g = = = = = = = A d d r e s s o f ;v a l u ei st h el o c a t i o no ft h eo p e r a n d C o n t e n t s o f ;v a l u ei sw h a ti ss t o r e da tt h el o c a t i o n N e g a t i o n V a l u e o fo p e r a t o r L o g i c a ln e g a t i o n(( ! E )i se q u i v a l e n tt o( 0 = = E )) B i t w i s ec o m p l e m e n t
Castoperators
Acastexpressionisaunaryexpression. Aparenthesizedtypenamefollowedbyacastexpressionisacastexpression.Theparenthesizedtypenamehastheeffectofforcingthecastexpressionintothetypespecifiedbythetypenameinparentheses.Forarithmetictypes,thiseitherdoesnot changethevalueoftheexpression,ortruncatesthevalueoftheexpressioniftheexpressionisanintegerandthenewtypeissmallerthantheprevioustype. Anexampleofcastingafloatasanint:
f l o a tp i=3 . 1 4 1 5 9 2 ; i n tt r u n c a t e d _ p i=( i n t ) p i ;/ /t r u n c a t e d _ p i= =3
Anexampleofcastingacharasanint:
c h a rm y _ c h a r=' A ' ; i n tm y _ i n t=( i n t ) m y _ c h a r ;/ /m y _ i n t= =6 5 ,w h i c hi st h eA S C I Iv a l u eo f' A '
Multiplicativeandadditiveoperators
InC,simplemathisveryeasytohandle.Thefollowingoperatorsexist:+(addition),(subtraction),*(multiplication),/(division),and%(modulus)Youlikelyknowallofthemfromyourmathclassesexcept,perhaps,modulus.Itreturnsthe remainder ofadivision(e.g.5%2=1). Caremustbetakenwiththemodulus,becauseit'snottheequivalentofthemathematicalmodulus:(5)%2isnot1,but1.Divisionofintegerswillreturnaninteger,andthedivisionofanegativeintegerbyapositiveintegerwillroundtowardszero insteadofroundingdown(e.g.(5)/3=1insteadof2). Thereisnoinlineoperatortodothepower(e.g.5^2is not25,and5**2isanerror),butthereisapowerfunction. Themathematicalorderofoperationsdoesapply.Forexample(2+3)*2=10while2+3*2=8.Multiplicativeoperatorshaveprecedenceoveradditiveoperators.
# i n c l u d e< s t d i o . h >
en.wikibooks.org/wiki/C_Programming/Print_version
24/118
10/24/13
i n tm a i n ( ) { i n ti=0 ,j=0 ; / *w h i l eii sl e s st h a n5A N Dji sl e s st h a n5 ,l o o p* / w h i l e (( i<5 )& &( j<5 )) { / *p o s t f i xi n c r e m e n t ,i + + * t h ev a l u eo fii sr e a da n dt h e ni n c r e m e n t e d * / p r i n t f ( " i :% d \ t " ,i + + ) ; / * *p r e f i xi n c r e m e n t ,+ + j * t h ev a l u eo fji si n c r e m e n t e da n dt h e nr e a d * / p r i n t f ( " j :% d \ n " ,+ + j ) ; } p r i n t f ( " A tt h ee n dt h e yh a v eb o t he q u a lv a l u e s : \ n i :% d \ t j :% d \ n " ,i ,j ) ; r e t u r n0 ; }
willdisplaythefollowing:
i :0 j :1 i :1 j :2 i :2 j :3 i :3 j :4 i :4 j :5 A tt h ee n dt h e yh a v eb o t he q u a lv a l u e s : i :5 j :5
shiftandrotate
ShiftfunctionsareoftenusedinlowlevelI/Ohardwareinterfacing.Shiftandrotatefunctionsareheavilyusedincryptographyandsoftwarefloatingpointemulation.Otherthanthat,shiftscanbeusedinplaceofdivisionormultiplicationbyapowerof two.ManyprocessorshavededicatedfunctionblockstomaketheseoperationsfastseeMicroprocessorDesign/ShiftandRotateBlocks.Onprocessorswhichhavesuchblocks,mostCcompilerscompileshiftandrotateoperatorstoasingleassembly languageinstructionseeX86Assembly/ShiftandRotate. shiftleft The < < operatorshiftsthebinaryrepresentationtotheleft,droppingthemostsignificantbitsandappendingitwithzerobits.Theresultisequivalenttomultiplyingtheintegerbyapoweroftwo. unsignedshiftright Theunsignedshiftrightoperator,alsosometimescalledthelogicalrightshiftoperator.Itshiftsthebinaryrepresentationtotheright,droppingtheleastsignificantbitsandprependingitwithzeros.The > > operatorisequivalenttodivisionbyapowerof twoforunsignedintegers. signedshiftright Thesignedshiftrightoperator,alsosometimescalledthearithmeticrightshiftoperator.Itshiftsthebinaryrepresentationtotheright,droppingtheleastsignificantbit,butprependingitwithcopiesoftheoriginalsignbit.The > > operatorisnotequivalent todivisionforsignedintegers. InC,thebehaviorofthe > > operatordependsonthedatatypeitactson.Therefore,asignedandanunsignedrightshiftlooksexactlythesame,butproducesadifferentresultinsomecases. rotateright Contrarytopopularbelief,itispossibletowriteCcodethatcompilesdowntothe"rotate"assemblylanguageinstruction(onCPUsthathavesuchaninstruction). Mostcompilersrecognizethisidiom:
u n s i g n e di n tx ; u n s i g n e di n ty ; / *. . .* / y=( x> >s h i f t )|( x< <( 3 2-s h i f t ) ) ;
en.wikibooks.org/wiki/C_Programming/Print_version
25/118
10/24/13
rotateleft Mostcompilersrecognizethisidiom:
u n s i g n e di n tx ; u n s i g n e di n ty ; / *. . .* / y=( x< <s h i f t )|( x> >( 3 2-s h i f t ) ) ;
andcompileittoasingle32bitrotateinstruction. Onsomesystems,thismaybe"#define"edasamacroordefinedasaninlinefunctioncalledsomethinglike"leftrotate32"or"rotl32"inaheaderfilelike"bitops.h".
Relationalandequalityoperators
Therelationalbinaryoperators < (lessthan), > (greaterthan), < = (lessthanorequal),and > = (greaterthanorequal)operatorsreturnavalueof1iftheresultoftheoperationistrue,0iffalse. Theequalitybinaryoperators = = (equals)and ! = (notequals)operatorsaresimilartotherelationaloperatorsexceptthattheirprecedenceislower.
Bitwiseoperators
Thebitwiseoperatorsare & (and), ^ (exclusiveor)and | (inclusiveor).The & operatorhashigherprecedencethan ^ ,whichhashigherprecedencethan | .
Logicaloperators
Thelogicaloperatorsare & & (and),and | | (or).Bothoftheseoperatorsproduce1iftherelationshipistrueand0forfalse.Bothoftheseoperatorsshortcircuitiftheresultoftheexpressioncanbedeterminedfromthefirstoperand,thesecondisignored.
& & isusedtoevaluateexpressionslefttoright,andreturnsa1if bothstatementsaretrue.
Here,the&&operatorcheckstheleftmostexpression,thentheexpressiontoit'sright.Sincebothstatementsreturntrue,the&&operatorreturnstrue,andthecodeblockisexecuted.
i f ( x= =5& &y= =5 ){ . . . }
The&&operatorchecksinthesamewayasbefore,andfindsthatthefirstexpressionisfalse.The&&operatorstopsevaluatingassoonasitfindsastatementtobefalse,andreturnsafalse.
| | isusedtoevaluateexpressionslefttoright,andreturnsa1if eitheroftheexpressionsaretrue.
Conditionaloperators
Theternary ? : operatoristheconditionaloperator.Theexpression ( x?y:z ) hasthevalueof y if x isnonzero, z otherwise. Example:
en.wikibooks.org/wiki/C_Programming/Print_version
26/118
10/24/13
Assignmentoperators
Theassignmentoperatorsare = , * = , / = , % = , + = , = , < < = , > > = , & = , ^ = ,and | = .The = operatorstoresthevalueoftherightoperandintothelocationdeterminedbytheleftoperand,whichmustbeanlvalue Fortheothers, xo p =y isshorthandfor x=xo p( y ) .Hence,thefollowingexpressionsarethesame:
1 .x+ =y 2 .x=y 3 .x* =y 4 .x/ =y 5 .x% =y x=x + y x=x y x=x * y x=x / y x=x % y
Commaoperator
Theoperatorwiththeleastprecedenceisthecommaoperator.Thevalueoftheexpression x ,y willevaluateboth x and y ,butprovidesthevalueof y . Thisoperatorisusefulforincludingmultipleactionsinonestatement(e.g.withinaforloopconditional). Herearesomesmallexamplesofthecommaoperator:
i n ti ,x ; / *d e c l a r e st w oi n t s ,ia n dx ,i no n es t a t e m e n t* /
1. Severalprogrammersrecommend"usespacesforindentation.Donotusetabsinyourcode.Youshouldsetyoureditortoemitspaceswhenyouhitthetabkey."[1](http://googlestyleguide.googlecode.com/svn/trunk/cppguide.xml)[2] (http://www.jwz.org/doc/tabsvsspaces.html)Otherprogrammersdisagree.[3](http://diagrammesmodernes.blogspot.com/2006/04/tabversusspaces.html)[4](http://www.derkarl.org/why_to_tabs.html)Regardlessofwhetheryoupreferspacesor tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5](http://www.oualline.com/vimcook.html#drawing) 3. [http://lxr.linux.no/#linux+v2.6.31/Documentation/CodingStyleLinuxKernelcodingstandard 4. "CodingConventionsforC++andJava"(http://www.macadamian.com/index.php?option=com_content&task=view&id=34&Itemid=37)"alltheblockcommentsillustratedinthisdocumenthavenoprettystarsontherightsideoftheblockcomment. Thisdeliberatechoicewasmadebecausealigningthoseprettystarsisalargewasteoftimeanddiscouragesthemaintenanceofinlinecomments.", 5. wiki:BigBlocksOfAsterisks,"Codecraft"(http://books.google.com/books? id=i4zCzpkrt4sC&pg=PA82&lpg=PA82&dq=programming+comment+block+waste+time+lining+up&source=bl&ots=TUpTMIHBnh&sig=NeZm23WPmvnw2aKMnIRUeQoHmJg&hl=en&ei=pri3SevGIYGyNMn9jd4K&sa=X&oi=book_result&resnum=8&ct=result) byPeteGoodliffepage82,Falvotech"CProgrammingStyleGuide"(http://www.falvotech.com/content/publications/conventions/c/),FedoraDirectoryServerCodingStyle(http://directory.fedoraproject.org/wiki/Coding_Style)
Furthermath
The < m a t h . h > headercontainsprototypesforseveralfunctionsthatdealwithmathematics.Inthe1990versionoftheISOstandard,onlythe d o u b l e versionsofthefunctionswerespecifiedthe1999versionaddedthe f l o a t and l o n gd o u b l e versions.Touse thesemathfunctions,youmustlinkyourprogramwiththemathlibrary.Forsomecompilers(includingGCC),youmustspecifytheadditionalparameter l m . Thefunctionscanbegroupedintothefollowingcategories:
Trigonometricfunctions
Thea c o s anda s i n functions
The a c o s functionsreturnthearccosineoftheirargumentsinradians,andthe a s i n functionsreturnthearcsineoftheirargumentsinradians.Allfunctionsexpecttheargumentintherange[1,+1].Thearccosinereturnsavalueintherange[0,]the arcsinereturnsavalueintherange[/2,+/2].
# i n c l u d e< m a t h . h > f l o a ta s i n f ( f l o a tx ) ;/ *C 9 9* / f l o a ta c o s f ( f l o a tx ) ;/ *C 9 9* / d o u b l ea s i n ( d o u b l ex ) ; d o u b l ea c o s ( d o u b l ex ) ; l o n gd o u b l ea s i n l ( l o n gd o u b l ex ) ;/ *C 9 9* / l o n gd o u b l ea c o s l ( l o n gd o u b l ex ) ;/ *C 9 9* /
en.wikibooks.org/wiki/C_Programming/Print_version
27/118
10/24/13
# i n c l u d e< m a t h . h > f l o a ta t a n f ( f l o a tx ) ;/ *C 9 9* / f l o a ta t a n 2 f ( f l o a ty ,f l o a tx ) ;/ *C 9 9* / d o u b l ea t a n ( d o u b l ex ) ; d o u b l ea t a n 2 ( d o u b l ey ,d o u b l ex ) ; l o n gd o u b l ea t a n l ( l o n gd o u b l ex ) ;/ *C 9 9* / l o n gd o u b l ea t a n 2 l ( l o n gd o u b l ey ,l o n gd o u b l ex ) ;/ *C 9 9* /
Hyperbolicfunctions
The c o s h , s i n h and t a n h functionscomputethehyperboliccosine,thehyperbolicsine,andthehyperbolictangentoftheargumentrespectively.Forthehyperbolicsineandcosinefunctions,arangeerroroccursifthemagnitudeoftheargumentistoolarge. The a c o s h functionscomputetheinversehyperboliccosineoftheargument.Adomainerroroccursforargumentslessthan1. The a s i n h functionscomputetheinversehyperbolicsineoftheargument. The a t a n h functionscomputetheinversehyperbolictangentoftheargument.Adomainerroroccursiftheargumentisnotintheinterval[1,+1].Arangeerrormayoccuriftheargumentequals1or+1.
# i n c l u d e< m a t h . h > f l o a tc o s h f ( f l o a tx ) ;/ *C 9 9* / f l o a ts i n h f ( f l o a tx ) ;/ *C 9 9* / f l o a tt a n h f ( f l o a tx ) ;/ *C 9 9* / d o u b l ec o s h ( d o u b l ex ) ; d o u b l es i n h ( d o u b l ex ) ; d o u b l et a n h ( d o u b l ex ) ; l o n gd o u b l ec o s h l ( l o n gd o u b l ex ) ;/ *C 9 9* / l o n gd o u b l es i n h l ( l o n gd o u b l ex ) ;/ *C 9 9* / l o n gd o u b l et a n h l ( l o n gd o u b l ex ) ;/ *C 9 9* / f l o a ta c o s h f ( f l o a tx ) ;/ *C 9 9* / f l o a ta s i n h f ( f l o a tx ) ;/ *C 9 9* / f l o a ta t a n h f ( f l o a tx ) ;/ *C 9 9* / d o u b l ea c o s h ( d o u b l ex ) ;/ *C 9 9* / d o u b l ea s i n h ( d o u b l ex ) ;/ *C 9 9* / d o u b l ea t a n h ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l ea c o s h l ( l o n gd o u b l ex ) ;/ *C 9 9* / l o n gd o u b l ea s i n h l ( l o n gd o u b l ex ) ;/ *C 9 9* / l o n gd o u b l ea t a n h l ( l o n gd o u b l ex ) ;/ *C 9 9* /
Exponentialandlogarithmicfunctions
Thee x p ,e x p 2 ,ande x p m 1 functions
The e x p functionscomputethebaseeexponentialfunctionof x (ex).Arangeerroroccursifthemagnitudeof x istoolarge. The e x p 2 functionscomputethebase2exponentialfunctionof x (2x).Arangeerroroccursifthemagnitudeof x istoolarge. The e x p m 1 functionscomputethebaseeexponentialfunctionoftheargument,minus1.Arangeerroroccursinthemagnitudeof x istoolarge.
# i n c l u d e< m a t h . h > f l o a te x p f ( f l o a tx ) ;/ *C 9 9* / d o u b l ee x p ( d o u b l ex ) ; l o n gd o u b l ee x p l ( l o n gd o u b l ex ) ;/ *C 9 9* / f l o a te x p 2 f ( f l o a tx ) ;/ *C 9 9* / d o u b l ee x p 2 ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l ee x p 2 l ( l o n gd o u b l ex ) ;/ *C 9 9* / f l o a te x p m 1 f ( f l o a tx ) ;/ *C 9 9* / d o u b l ee x p m 1 ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l ee x p m 1 l ( l o n gd o u b l ex ) ;/ *C 9 9* /
en.wikibooks.org/wiki/C_Programming/Print_version
28/118
10/24/13
Thef r e x p ,l d e x p ,m o d f ,s c a l b n ,ands c a l b l n functions
The f r e x p functionsbreaktheargumentfloatingpointnumber v a l u e intothosetwoparts,theexponentandsignificand.Afterbreakingitapart,itstorestheexponentinthe i n t objectpointedtoby e x ,andreturnsthesignificand.Inotherwords,thevalue returnedisacopyofthegivenfloatingpointnumberbutwithanexponentreplacedby0.If v a l u e iszero,bothpartsoftheresultarezero. The l d e x p functionsmultiplyafloatingpointnumberbyaintegralpowerof2andreturntheresult.Inotherwords,itreturnscopyofthegivenfloatingpointnumberwiththeexponentincreasedbyex.Arangeerrormayoccur. The m o d f functionsbreaktheargument v a l u e intointegerandfractionparts,eachofwhichhasthesamesignastheargument.Theystoretheintegerpartintheobjectpointedtoby * i p t r andreturnthefractionpart.The * i p t r isafloatingpointtype,rather thanan"int"type,becauseitmightbeusedtostoreanintegerlike1000000000000000000000whichistoobigtofitinanint.
n The s c a l b n and s c a l b l n compute x F L T _ R A D I X . F L T _ R A D I X isthebaseofthefloatingpointsystemifitis2,thefunctionsareequivalentto l d e x p .
# i n c l u d e< m a t h . h > f l o a tf r e x p f ( f l o a tv a l u e ,i n t* e x ) ;/ *C 9 9* / d o u b l ef r e x p ( d o u b l ev a l u e ,i n t* e x ) ; l o n gd o u b l ef r e x p l ( l o n gd o u b l ev a l u e ,i n t* e x ) ;/ *C 9 9* / f l o a tl d e x p f ( f l o a tx ,i n te x ) ;/ *C 9 9* / d o u b l el d e x p ( d o u b l ex ,i n te x ) ; l o n gd o u b l el d e x p l ( l o n gd o u b l ex ,i n te x ) ;/ *C 9 9* / f l o a tm o d f f ( f l o a tv a l u e ,f l o a t* i p t r ) ;/ *C 9 9* / d o u b l em o d f ( d o u b l ev a l u e ,d o u b l e* i p t r ) ; l o n gd o u b l em o d f l ( l o n gd o u b l ev a l u e ,l o n gd o u b l e* i p t r ) ;/ *C 9 9* / f l o a ts c a l b n f ( f l o a tx ,i n te x ) ;/ *C 9 9* / d o u b l es c a l b n ( d o u b l ex ,i n te x ) ;/ *C 9 9* / l o n gd o u b l es c a l b n l ( l o n gd o u b l ex ,i n te x ) ;/ *C 9 9* / f l o a ts c a l b l n f ( f l o a tx ,l o n gi n te x ) ;/ *C 9 9* / d o u b l es c a l b l n ( d o u b l ex ,l o n gi n te x ) ;/ *C 9 9* / l o n gd o u b l es c a l b l n l ( l o n gd o u b l ex ,l o n gi n te x ) ;/ *C 9 9* /
MostCfloatingpointlibrariesalsoimplementtheIEEE754recommendednextafter(),nextUp(),andnextDown()functions.[6](http://www.opengroup.org/onlinepubs/009695399/functions/nextafter.html)
# i n c l u d e< m a t h . h > i n ti l o g b f ( f l o a tx ) ;/ *C 9 9* /
en.wikibooks.org/wiki/C_Programming/Print_version
29/118
10/24/13
i n ti l o g b ( d o u b l ex ) ;/ *C 9 9* / i n td o u b l ei l o g b l ( l o n gd o u b l ex ) ;/ *C 9 9* / f l o a tl o g b f ( f l o a tx ) ;/ *C 9 9* / d o u b l el o g b ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l el o g b l ( l o n gd o u b l ex ) ;/ *C 9 9* /
Powerfunctions
Thep o w functions
The p o w functionscompute x raisedtothepower y andreturntheresult.Adomainerroroccursif x isnegativeand y isnotanintegralvalue.Adomainerroroccursiftheresultcannotberepresentedwhen x iszeroand y islessthanorequaltozero.A rangeerrormayoccur.
# i n c l u d e< m a t h . h > f l o a tp o w f ( f l o a tx ,f l o a ty ) ;/ *C 9 9* / d o u b l ep o w ( d o u b l ex ,d o u b l ey ) ; l o n gd o u b l ep o w l ( l o n gd o u b l ex ,l o n gd o u b l ey ) ;/ *C 9 9* /
Thes q r t functions
The s q r t functionscomputethepositivesquarerootof x andreturntheresult.Adomainerroroccursiftheargumentisnegative.
# i n c l u d e< m a t h . h > f l o a ts q r t f ( f l o a tx ) ;/ *C 9 9* / d o u b l es q r t ( d o u b l ex ) ; l o n gd o u b l es q r t l ( l o n gd o u b l ex ) ;/ *C 9 9* /
Thec b r t functions
The c b r t functionscomputethecuberootof x andreturntheresult.
# i n c l u d e< m a t h . h > f l o a tc b r t f ( f l o a tx ) ;/ *C 9 9* / d o u b l ec b r t ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l ec b r t l ( l o n gd o u b l ex ) ;/ *C 9 9* /
Theh y p o t functions
The h y p o t functionscomputethesquarerootofthesumsofthesquaresof x and y ,withoutoverfloworunderflow,andreturntheresult.
# i n c l u d e< m a t h . h > f l o a th y p o t f ( f l o a tx ,f l o a ty ) ;/ *C 9 9* / d o u b l eh y p o t ( d o u b l ex ,d o u b l ey ) ;/ *C 9 9* / l o n gd o u b l eh y p o t l ( l o n gd o u b l ex ,l o n gd o u b l ey ) ;/ *C 9 9* /
Nearestinteger,absolutevalue,andremainderfunctions
Thec e i l andf l o o r functions
The c e i l functionscomputethesmallestintegralvaluenotlessthan x andreturntheresultthe f l o o r functionscomputethelargestintegralvaluenotgreaterthan x andreturntheresult.
# i n c l u d e< m a t h . h > f l o a tc e i l f ( f l o a tx ) ;/ *C 9 9* / d o u b l ec e i l ( d o u b l ex ) ; l o n gd o u b l ec e i l l ( l o n gd o u b l ex ) ;/ *C 9 9* / f l o a tf l o o r f ( f l o a tx ) ;/ *C 9 9* / d o u b l ef l o o r ( d o u b l ex ) ; l o n gd o u b l ef l o o r l ( l o n gd o u b l ex ) ;/ *C 9 9* /
Thef a b s functions
The f a b s functionscomputetheabsolutevalueofafloatingpointnumber x andreturntheresult.
# i n c l u d e< m a t h . h > f l o a tf a b s f ( f l o a tx ) ;/ *C 9 9* / d o u b l ef a b s ( d o u b l ex ) ; l o n gd o u b l ef a b s l ( l o n gd o u b l ex ) ;/ *C 9 9* /
en.wikibooks.org/wiki/C_Programming/Print_version
30/118
10/24/13
Thef m o d functions
The f m o d functionscomputethefloatingpointremainderof x / y andreturnthevalue x i* y ,forsomeinteger isuchthat,if y isnonzero,theresulthasthesamesignas x andmagnitudelessthanthemagnitudeof y .If y iszero,whetheradomainerror occursorthe f m o d functionsreturnzeroisimplementationdefined.
# i n c l u d e< m a t h . h > f l o a tf m o d f ( f l o a tx ,f l o a ty ) ;/ *C 9 9* / d o u b l ef m o d ( d o u b l ex ,d o u b l ey ) ; l o n gd o u b l ef m o d l ( l o n gd o u b l ex ,l o n gd o u b l ey ) ;/ *C 9 9* /
Thet r u n c functions
The t r u n c functionsroundtheirargumenttotheintegervalueinfloatingpointformatthatisnearestbutnolargerinmagnitudethantheargument.
# i n c l u d e< m a t h . h > f l o a tt r u n c f ( f l o a tx ) ;/ *C 9 9* / d o u b l et r u n c ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l et r u n c l ( l o n gd o u b l ex ) ;/ *C 9 9* /
Ther e m a i n d e r functions
The r e m a i n d e r functionscomputetheremainder x REM y asdefinedbyIEC60559.Thedefinitionreads,"When y0,theremainder r= xREM yisdefinedregardlessoftheroundingmodebythemathematicalreduction r= x ny,where nistheinteger nearesttheexactvalueof x/ ywhenever|n x/ y|=,then niseven.Thus,theremainderisalwaysexact.If r=0,itssignshallbethatof x."Thisdefinitionisapplicableforallimplementations.
# i n c l u d e< m a t h . h > f l o a tr e m a i n d e r f ( f l o a tx ,f l o a ty ) ;/ *C 9 9* / d o u b l er e m a i n d e r ( d o u b l ex ,d o u b l ey ) ;/ *C 9 9* / l o n gd o u b l er e m a i n d e r l ( l o n gd o u b l ex ,l o n gd o u b l ey ) ;/ *C 9 9* /
Ther e m q u o functions
en.wikibooks.org/wiki/C_Programming/Print_version
31/118
10/24/13
Errorandgammafunctions
The e r f functionscomputetheerrorfunctionoftheargument(2/() 0x et dt)the e r f c functionscomputethecomplimentaryerrorfunctionoftheargument(thatis,1erfx).Forthe e r f c functions,arangeerrormayoccuriftheargumentistoolarge. The l g a m m a functionscomputethenaturallogarithmoftheabsolutevalueofthegammaoftheargument(thatis,loge|(x)|).Arangeerrormayoccuriftheargumentisanegativeintegerorzero. The t g a m m a functionscomputethegammaoftheargument(thatis,(x)).Adomainerroroccursiftheargumentisanegativeintegeroriftheresultcannotberepresentedwhentheargumentiszero.Arangeerrormayoccur.
# i n c l u d e< m a t h . h > f l o a te r f f ( f l o a tx ) ;/ *C 9 9* / d o u b l ee r f ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l ee r f l ( l o n gd o u b l ex ) ;/ *C 9 9* / f l o a te r f c f ( f l o a tx ) ;/ *C 9 9* / d o u b l ee r f c ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l ee r f c l ( l o n gd o u b l ex ) ;/ *C 9 9* / f l o a tl g a m m a f ( f l o a tx ) ;/ *C 9 9* / d o u b l el g a m m a ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l el g a m m a l ( l o n gd o u b l ex ) ;/ *C 9 9* / f l o a tt g a m m a f ( f l o a tx ) ;/ *C 9 9* / d o u b l et g a m m a ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l et g a m m a l ( l o n gd o u b l ex ) ;/ *C 9 9* /
2
Furtherreading
1. Severalprogrammersrecommend"usespacesforindentation.Donotusetabsinyourcode.Youshouldsetyoureditortoemitspaceswhenyouhitthetabkey."[1](http://googlestyleguide.googlecode.com/svn/trunk/cppguide.xml)[2] (http://www.jwz.org/doc/tabsvsspaces.html)Otherprogrammersdisagree.[3](http://diagrammesmodernes.blogspot.com/2006/04/tabversusspaces.html)[4](http://www.derkarl.org/why_to_tabs.html)Regardlessofwhetheryoupreferspacesor tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5](http://www.oualline.com/vimcook.html#drawing) 3. [http://lxr.linux.no/#linux+v2.6.31/Documentation/CodingStyleLinuxKernelcodingstandard 4. "CodingConventionsforC++andJava"(http://www.macadamian.com/index.php?option=com_content&task=view&id=34&Itemid=37)"alltheblockcommentsillustratedinthisdocumenthavenoprettystarsontherightsideoftheblockcomment. Thisdeliberatechoicewasmadebecausealigningthoseprettystarsisalargewasteoftimeanddiscouragesthemaintenanceofinlinecomments.", 5. wiki:BigBlocksOfAsterisks,"Codecraft"(http://books.google.com/books? id=i4zCzpkrt4sC&pg=PA82&lpg=PA82&dq=programming+comment+block+waste+time+lining+up&source=bl&ots=TUpTMIHBnh&sig=NeZm23WPmvnw2aKMnIRUeQoHmJg&hl=en&ei=pri3SevGIYGyNMn9jd4K&sa=X&oi=book_result&resnum=8&ct=result) byPeteGoodliffepage82,Falvotech"CProgrammingStyleGuide"(http://www.falvotech.com/content/publications/conventions/c/),FedoraDirectoryServerCodingStyle(http://directory.fedoraproject.org/wiki/Coding_Style)
Control
Veryfewprogramsfollowexactlyonecontrolpathandhaveeachinstructionstatedexplicitly.Inordertoprogrameffectively,itisnecessarytounderstandhowonecanalterthestepstakenbyaprogramduetouserinputorotherconditions,howsome stepscanbeexecutedmanytimeswithfewlinesofcode,andhowprogramscanappeartodemonstratearudimentarygraspoflogic.Cconstructsknownasconditionalsandloopsgrantthispower. Fromthispointforward,itisnecessarytounderstandwhatisusuallymeantbytheword block.Ablockisagroupofcodestatementsthatareassociatedandintendedtobeexecutedasaunit.InC,thebeginningofablockofcodeisdenotedwith{(left curly),andtheendofablockisdenotedwith}.Itisnotnecessarytoplaceasemicolonaftertheendofablock.Blockscanbeempty,asin{}.Blockscanalsobenestedi.e.therecanbeblocksofcodewithinlargerblocks.
Conditionals
Thereislikelynomeaningfulprogramwritteninwhichacomputerdoesnotdemonstratebasicdecisionmakingskills.Itcanactuallybearguedthatthereisnomeaningfulhumanactivityinwhichsomesortofdecisionmaking,instinctualorotherwise, doesnottakeplace.Forexample,whendrivingacarandapproachingatrafficlight,onedoesnotthink,"Iwillcontinuedrivingthroughtheintersection."Rather,onethinks,"Iwillstopifthelightisred,goifthelightisgreen,andifyellowgoonlyifIam travelingatacertainspeedacertaindistancefromtheintersection."ThesekindsofprocessescanbesimulatedinCusingconditionals. Aconditionalisastatementthatinstructsthecomputertoexecuteacertainblockofcodeoraltercertaindataonlyifaspecificconditionhasbeenmet.ThemostcommonconditionalistheIfElsestatement,withconditionalexpressionsandSwitchCase statementstypicallyusedasmoreshorthandedmethods. Beforeonecanunderstandconditionalstatements,itisfirstnecessarytounderstandhowCexpresseslogicalrelations.Ctreatslogicasbeingarithmetic.Thevalue0(zero)representsfalse,and allothervaluesrepresenttrue.Ifyouchosesome particularvaluetorepresenttrueandthencomparevaluesagainstit,soonerorlateryourcodewillfailwhenyourassumedvalue(often1)turnsouttobeincorrect.CodewrittenbypeopleuncomfortablewiththeClanguagecanoftenbeidentifiedbythe usageof#definetomakea"TRUE"value. [4] BecauselogicisarithmeticinC,arithmeticoperatorsandlogicaloperatorsareoneandthesame.Nevertheless,thereareanumberofoperatorsthataretypicallyassociatedwithlogic:
en.wikibooks.org/wiki/C_Programming/Print_version
32/118
10/24/13
RelationalandEquivalenceExpressions:
a<b 1if aislessthan b,0otherwise. a>b 1if aisgreaterthan b,0otherwise. a<=b 1if aislessthanorequalto b,0otherwise. a>=b 1if aisgreaterthanorequalto b,0otherwise. a==b 1if aisequalto b,0otherwise. a!=b 1if aisnotequalto b,0otherwise
Newprogrammersshouldtakespecialnoteofthefactthatthe"equalto"operatoris==,not=.Thisisthecauseofnumerouscodingmistakesandisoftenadifficulttofindbug,astheexpression ( a=b ) sets a equalto b andsubsequentlyevaluatesto b buttheexpression ( a= =b ) ,whichisusuallyintended,checksif a isequalto b .Itneedstobepointedoutthat,ifyouconfuse=with==,yourmistakewilloftennotbebroughttoyourattentionbythecompiler.Astatementsuchas i f(c=2 0 ){ } is consideredperfectlyvalidbythelanguage,butwillalwaysassign20to c andevaluateastrue.Asimpletechniquetoavoidthiskindofbug(inmany,notallcases)istoputtheconstantfirst.Thiswillcausethecompilertoissueanerror,if==got misspelledwith=. NotethatCdoesnothaveadedicatedbooleantypeasmanyotherlanguagesdo.0meansfalseandanythingelsetrue.Sothefollowingareequivalent:
i f( f o o ( ) ){ / / d os o m e t h i n g }
and
i f( f o o ( )! =0 ){ / / d os o m e t h i n g }
Here, s t r s t r returnstheindexwherethesubstringfooisfoundand1ifitwasnotfound.Notethatthiswouldfailwiththe T R U E definitionmentionedinthepreviousparagraph.Itwouldalsonotproducetheexpectedresultsifweomittedthe > =0 . Oneotherthingtonoteisthattherelationalexpressionsdonotevaluateastheywouldinmathematicaltexts.Thatis,anexpression m y M i n<v a l u e<m y M a x doesnotevaluateasyouprobablythinkitmight.Mathematically,thiswouldtestwhetherornot value isbetween myMinand myMax.ButinC,whathappensisthat valueisfirstcomparedwith myMin.Thisproduceseithera0ora1.ItisthisvaluethatiscomparedagainstmyMax.Example:
i n tv a l u e=2 0 ; / *. . .* / i f(0<v a l u e<1 0 ){/ /d o n ' td ot h i s !i ta l w a y se v a l u a t e st o" t r u e " ! / *d os o m es t u f f* / }
Because valueisgreaterthan0,thefirstcomparisonproducesavalueof1.Now1iscomparedtobelessthan10,whichistrue,sothestatementsintheifareexecuted.Thisprobablyisnotwhattheprogrammerexpected.Theappropriatecodewould be
i n tv a l u e=2 0 ; / *. . .* / i f(0<v a l u e& &v a l u e<1 0 ){ / /t h e& &m e a n s" a n d " / *d os o m es t u f f* / }
LogicalExpressions
a||b whenEITHER aor bistrue(orboth),theresultis1,otherwisetheresultis0. a&&b whenBOTH aand baretrue,theresultis1,otherwisetheresultis0.
en.wikibooks.org/wiki/C_Programming/Print_version
33/118
10/24/13
!a when aistrue,theresultis0,when ais0,theresultis1. Here'sanexampleofalargerlogicalexpression.Inthestatement:
e=( ( a& &b )| |( c>d ) ) ;
eissetequalto1ifaandbarenonzero,orifcisgreaterthand.Inallothercases,eissetto0. Cusesshortcircuitevaluationoflogicalexpressions.Thatistosay,onceitisabletodeterminethetruthofalogicalexpression,itdoesnofurtherevaluation.Thisisoftenusefulasinthefollowing:
i n tm y A r r a y [ 1 2 ] ; . . . . i f(i<1 2& &m y A r r a y [ i ]>3 ){ . . . .
doThat()isnevercalledifdoThis()returnsanonzero(true)value.
BitwiseBooleanExpressions
Thebitwiseoperatorsworkbitbybitontheoperands.Theoperandsmustbeofintegraltype(oneofthetypesusedforintegers).Thesixbitwiseoperatorsare&(AND),|(OR),^(exclusiveOR,commonlycalledXOR),~(NOT,whichchanges1to0and0 to1),<<(shiftleft),and>>(shiftright).Thenegationoperatorisaunaryoperatorwhichprecedestheoperand.Theothersarebinaryoperatorswhichliebetweenthetwooperands.Theprecedenceoftheseoperatorsislowerthanthatoftherelationaland equivalenceoperatorsitisoftenrequiredtoparenthesizeexpressionsinvolvingbitwiseoperators. Forthissection,recallthatanumberstartingwith 0xishexadecimal,orhexforshort.Unlikethenormaldecimalsystemusingpowersof10anddigits0123456789,hexusespowersof16anddigits0123456789abcdef.Hexadecimaliscommonlyusedin Cprogramsbecauseaprogrammercanquicklyconvertittoorfrombinary(powersof2anddigits01).Cdoesnotdirectlysupportbinarynotation,whichwouldbereallyverboseanyway. a&b bitwisebooleanandof aand b 0xc&0xaproducesthevalue0x8(inbinary,1100&1010produces1000) a|b bitwisebooleanorof aand b 0xc|0xaproducesthevalue0xe(inbinary,1100|1010produces1110) a^b bitwisexorof aand b 0xc^0xaproducesthevalue0x6(inbinary,1100^1010produces0110) ~a bitwisecomplementof a. ~0xcproducesthevalue10xc(inbinary,~1100produces...11110011where"..."maybemanymore1bits) a<<b shift aleftby b(multiplyaby ) 0xc<<1producesthevalue0x18(inbinary,1100<<1producesthevalue11000) a>>b shift arightby b(divideaby ) 0xc>>1producesthevalue0x6(inbinary,1100>>1producesthevalue110)
TheIfElsestatement
IfElseprovidesawaytoinstructthecomputertoexecuteablockofcodeonlyifcertainconditionshavebeenmet.ThesyntaxofanIfElseconstructis:
i f( / *c o n d i t i o ng o e sh e r e* / ){ / *i ft h ec o n d i t i o ni sn o n z e r o( t r u e ) ,t h i sc o d ew i l le x e c u t e* / }e l s e{ / *i ft h ec o n d i t i o ni s0( f a l s e ) ,t h i sc o d ew i l le x e c u t e* / }
en.wikibooks.org/wiki/C_Programming/Print_version
34/118
10/24/13
Thefirstblockofcodeexecutesiftheconditioninparenthesesdirectlyafterthe if evaluatestononzero(true)otherwise,thesecondblockexecutes. The elseandfollowingblockofcodearecompletelyoptional.Ifthereisnoneedtoexecutecodeifaconditionisnottrue,leaveitout. Also,keepinmindthatan if candirectlyfollowan elsestatement.Whilethiscanoccasionallybeuseful,chainingmorethantwoorthreeifelsesinthisfashionisconsideredbadprogrammingpractice.WecangetaroundthiswiththeSwitchCase constructdescribedlater. Twoothergeneralsyntaxnotesneedtobemadethatyouwillalsoseeinothercontrolconstructs:First,notethatthereisnosemicolonafter if or else.Therecouldbe,buttheblock(codeenclosedin{and})takestheplaceofthat.Second,ifyouonly intendtoexecuteonestatementasaresultofan if or else,curlybracesarenotneeded.However,manyprogrammersbelievethatinsertingcurlybracesanywayinthiscaseisgoodcodingpractice. Thefollowingcodesetsavariablecequaltothegreateroftwovariablesaandb,or0ifaandbareequal.
i f ( a>b ){ c=a ; }e l s ei f ( b>a ){ c=b ; }e l s e{ c=0 ; }
Considerthisquestion:whycan'tyoujustforgetabout elseandwritethecodelike:
i f ( a>b ){ c=a ; } i f ( a<b ){ c=b ; } i f ( a= =b ){ c=0 ; }
Thereareseveralanswerstothis.Mostimportantly,ifyourconditionalsarenotmutuallyexclusive, twocasescouldexecuteinsteadofonlyone.Ifthecodewasdifferentandthevalueofaorbchangessomehow(e.g.:youresetthelesserofaandbto0 afterthecomparison)duringoneoftheblocks?Youcouldendupwithmultiple if statementsbeinginvoked,whichisnotyourintent.Also,evaluating if conditionalstakesprocessortime.Ifyouuse elsetohandlethesesituations,inthecaseabove assuming(a>b)isnonzero(true),theprogramissparedtheexpenseofevaluatingadditional if statements.Thebottomlineisthatitisusuallybesttoinsertan elseclauseforallcasesinwhichaconditionalwillnotevaluatetononzero(true). Theconditionalexpression AconditionalexpressionisawaytosetvaluesconditionallyinamoreshorthandfashionthanIfElse.Thesyntaxis:
( / *l o g i c a le x p r e s s i o ng o e sh e r e* / )?( / *i fn o n z e r o( t r u e )* / ):( / *i f0( f a l s e )* / )
Thelogicalexpressionisevaluated.Ifitisnonzero(true),theoverallconditionalexpressionevaluatestotheexpressionplacedbetweenthe?and:,otherwise,itevaluatestotheexpressionafterthe:.Therefore,theaboveexample(changingitsfunction slightlysuchthatcissettobwhenaandbareequal)becomes:
c=( a>b )?a:b ;
Conditionalexpressionscansometimesclarifytheintentofthecode.Nestingtheconditionaloperatorshouldusuallybeavoided.It'sbesttouseconditionalexpressionsonlywhentheexpressionsforaandbaresimple.Also,contrarytoacommon beginnerbelief,conditionalexpressionsdonotmakeforfastercode.Astemptingasitistoassumethatfewerlinesofcoderesultinfasterexecutiontimes,thereisnosuchcorrelation.
TheSwitchCasestatement
Sayyouwriteaprogramwheretheuserinputsanumber15(correspondingtostudentgrades,A(representedas1)D(4)andF(5)),storesitinavariable gradeandtheprogramrespondsbyprintingtothescreentheassociatedlettergrade.Ifyou implementedthisusingIfElse,yourcodewouldlooksomethinglikethis:
i f ( g r a d e= =1 ){ p r i n t f ( " A \ n " ) ; }e l s ei f ( g r a d e= =2 ){ p r i n t f ( " B \ n " ) ; }e l s ei f/ *e t c .e t c .* /
Havingalongchainofifelseifelseifelsecanbeapain,bothfortheprogrammerandanyonereadingthecode.Fortunately,there'sasolution:theSwitchCaseconstruct,ofwhichthebasicsyntaxis:
s w i t c h ( / *i n t e g e ro re n u mg o e sh e r e* / ){ c a s e/ *p o t e n t i a lv a l u eo ft h ea f o r e m e n t i o n e di n to re n u m* / : / *c o d e* / c a s e/ *ad i f f e r e n tp o t e n t i a lv a l u e* / : / *d i f f e r e n tc o d e* /
en.wikibooks.org/wiki/C_Programming/Print_version
35/118
10/24/13
/ *i n s e r ta d d i t i o n a lc a s e sa sn e e d e d* / d e f a u l t : / *m o r ec o d e* / }
TheSwitchCaseconstructtakesavariable,usuallyanintoranenum,placedafter switch,andcomparesittothevaluefollowingthe casekeyword.Ifthevariableisequaltothevaluespecifiedafter case,theconstruct"activates",orbeginsexecutingthe codeafterthecasestatement.Oncetheconstructhas"activated",therewillbenofurtherevaluationof cases. SwitchCaseissyntactically"weird"inthatnobracesarerequiredforcodeassociatedwitha case. Veryimportant:Typically,thelaststatementforeachcaseisabreakstatement.Thiscausesprogramexecutiontojumptothestatementfollowingtheclosingbracketoftheswitchstatement,whichiswhatonewouldnormallywanttohappen.However ifthebreakstatementisomitted,programexecutioncontinueswiththefirstlineofthenextcase,ifany.Thisiscalleda fallthrough.Whenaprogrammerdesiresthisaction,acommentshouldbeplacedattheendoftheblockofstatementsindicating thedesiretofallthrough.Otherwiseanotherprogrammermaintainingthecodecouldconsidertheomissionofthe'break'tobeanerror,andinadvertently'correct'theproblem.Here'sanexample:
s w i t c h(s o m e V a r i a b l e){ c a s e1 : p r i n t f ( " T h i sc o d eh a n d l e sc a s e1 \ n " ) ; b r e a k ; c a s e2 : p r i n t f ( " T h i sp r i n t sw h e ns o m e V a r i a b l ei s2 ,a l o n gw i t h . . . \ n " ) ; / *F A L LT H R O U G H* / c a s e3 : p r i n t f ( " T h i sp r i n t sw h e ns o m e V a r i a b l ei se i t h e r2o r3 . \ n ") ; b r e a k ; }
Asetofstatementstoexecutecanbegroupedwithmorethanonevalueofthevariableasinthefollowingexample.(thefallthroughcommentisnotnecessaryherebecausetheintendedbehaviorisobvious)
s w i t c h( s o m e t h i n g ){ c a s e2 : c a s e3 : c a s e4 : / *s o m es t a t e m e n t st oe x e c u t ef o r2 ,3o r4* / b r e a k ; c a s e1 : d e f a u l t : / *s o m es t a t e m e n t st oe x e c u t ef o r1o ro t h e rt h a n2 , 3 , a n d4* / b r e a k ; }
SwitchCaseconstructsareparticularlyusefulwhenusedinconjunctionwithuserdefined enumdatatypes.Somecompilersarecapableofwarningaboutanunhandledenumvalue,whichmaybehelpfulforavoidingbugs.
Loops
Oftenincomputerprogramming,itisnecessarytoperformacertainactionacertainnumberoftimesoruntilacertainconditionismet.Itisimpracticalandtedioustosimplytypeacertainstatementorgroupofstatementsalargenumberoftimes,notto mentionthatthisapproachistooinflexibleandunintuitivetobecountedontostopwhenacertaineventhashappened.Asarealworldanalogy,someoneasksadishwasheratarestaurantwhathedidallnight.Hewillrespond,"Iwasheddishesallnight long."Heisnotlikelytorespond,"Iwashedadish,thenwashedadish,thenwashedadish,then...".Theconstructsthatenablecomputerstoperformcertainrepetitivetasksarecalledloops.
Whileloops
Awhileloopisthemostbasictypeofloop.Itwillrunaslongastheconditionisnonzero(true).Forexample,ifyoutrythefollowing,theprogramwillappeartolockupandyouwillhavetomanuallyclosetheprogramdown.Asituationwherethe conditionsforexitingtheloopwillneverbecometrueiscalledaninfiniteloop.
i n ta = 1 ;
en.wikibooks.org/wiki/C_Programming/Print_version
36/118
10/24/13
w h i l e ( 4 2 ){ a=a * 2 ; }
Hereisanotherexampleofawhileloop.Itprintsoutallthepowersoftwolessthan100.
i n ta = 1 ; w h i l e ( a < 1 0 0 ){ p r i n t f ( " ai s% d\ n " , a ) ; a=a * 2 ; }
Inthisexample,thecomputerprintsthevalueofaasusual,andprintsanoticethataisnot64(unlessitwasskippedbythecontinuestatement). SimilartoIfabove,bracesfortheblockofcodeassociatedwithaWhileloopcanbeomittedifthecodeconsistsofonlyonestatement,forexample:
i n ta = 1 ; w h i l e ( a<1 0 0 )a=a * 2 ;
Thisexecutesthecodeinthewhileloop5times,withihavingvaluesthatrangefrom4downto0(insidetheloop).Conveniently,thesearethevaluesneededtoaccesseveryitemofanarraycontaining5elements.
Forloops
Forloopsgenerallylooksomethinglikethis:
f o r ( i n i t i a l i z a t i o n ;t e s t ;i n c r e m e n t ){ / *c o d e* / }
The initializationstatementisexecutedexactlyoncebeforethefirstevaluationofthe test condition.Typically,itisusedtoassignaninitialvaluetosomevariable,althoughthisisnotstrictlynecessary.The initializationstatementcanalsobeusedto declareandinitializevariablesusedintheloop. The test expressionisevaluatedeachtimebeforethecodeinthe forloopexecutes.Ifthisexpressionevaluatesas0(false)whenitischecked(i.e.iftheexpressionisnottrue),theloopisnot(re)enteredandexecutioncontinuesnormallyatthecode immediatelyfollowingtheFORloop.Iftheexpressionisnonzero(true),thecodewithinthebracesoftheloopisexecuted. Aftereachiterationoftheloop,the increment statementisexecuted.Thisoftenisusedtoincrementtheloopindexfortheloop,thevariableinitializedintheinitializationexpressionandtestedinthetestexpression.Followingthisstatementexecution, controlreturnstothetopoftheloop,wherethe test actionoccurs.Ifa continuestatementisexecutedwithinthe forloop,theincrementstatementwouldbethenextoneexecuted. Eachofthesepartsoftheforstatementisoptionalandmaybeomitted.Becauseofthefreeformnatureoftheforstatement,somefairlyfancythingscanbedonewithit.Oftenaforloopisusedtoloopthroughitemsinanarray,processingeachitemat atime.
en.wikibooks.org/wiki/C_Programming/Print_version
37/118
10/24/13
i n t m y A r r a y [ 1 2 ] ; i n ti x ; f o r( i x=0 ;i x < 1 2 ;i x + + ){ m y A r r a y [ i x ]=5*i x+3 ; }
Theaboveforloopinitializeseachofthe12elementsofmyArray.Theloopindexcanstartfromanyvalue.Inthefollowingcaseitstartsfrom1.
f o r ( i x=1 ;i x< =1 0 ;i x + + ){ p r i n t f ( " % d" ,i x ) ; }
whichwillprint
1234567891 0
whichyields
54321
Here'sanexamplewherethetestconditionissimplyavariable.Ifthevariablehasavalueof0orNULL,theloopexits,otherwisethestatementsinthebodyoftheloopareexecuted.
f o r( t=l i s t _ h e a d ;t ;t=N e x t I t e m ( t )){ / * b o d yo fl o o p* / }
AWHILEloopcanbeusedtodothesamethingasaFORloop,howeveraFORloopisamorecondensedwaytoperformasetnumberofrepetitionssinceallofthenecessaryinformationisinaonelinestatement. AFORloopcanalsobegivennoconditions,forexample:
f o r ( ; ; ){ / *b l o c ko fs t a t e m e n t s* / }
Thisiscalledaninfiniteloopsinceitwillloopforeverunlessthereisabreakstatementwithinthestatementsoftheforloop.Theemptytestconditioneffectivelyevaluatesastrue. Itisalsocommontousethecommaoperatorinforloopstoexecutemultiplestatements.
i n ti ,j ,n=1 0 ; f o r ( i=0 ,j=0 ;i< =n ;i + + , j + = 2 ){ p r i n t f ( " i=% d,j=% d\ n " , i , j ) ; }
Specialcareshouldbetakenwhendesigningorrefactoringtheconditionalpart,especiallywhetherusing<or<=,whetherstartandstopshouldbecorrectedby1,andincaseofprefixandpostfixnotations.(Ona100yardspromenadewithatreeevery 10yardsthereare11trees.)
i n ti ,n=1 0 ; f o r ( i=0 ;i<n ;i + + )p r i n t f ( " % d" , i ) ;/ /p r o c e s s e dnt i m e s= >0123. . .( n 1 ) p r i n t f ( " \ n " ) ; f o r ( i=0 ;i< =n ;i + + )p r i n t f ( " % d" , i ) ;/ /p r o c e s s e d( n + 1 )t i m e s= >0123. . .n p r i n t f ( " \ n " ) ; f o r ( i=n ;i ; )p r i n t f ( " % d" , i ) ;/ /p r o c e s s e dnt i m e s= >( n 1 ). . . 3210 p r i n t f ( " \ n " ) ; f o r ( i=n ;i ; )p r i n t f ( " % d" , i ) ;/ /p r o c e s s e d( n 1 )t i m e s= >( n 1 ). . . 4321 p r i n t f ( " \ n " ) ;
DoWhileloops
en.wikibooks.org/wiki/C_Programming/Print_version
38/118
10/24/13
ADOWHILEloopisapostcheckwhileloop,whichmeansthatitcheckstheconditionaftereachrun.Asaresult,eveniftheconditioniszero(false),itwillrunatleastonce.Itfollowstheformof:
d o{ / *d os t u f f* / }w h i l e( c o n d i t i o n ) ;
Onelastthing:goto
gotoisaverysimpleandtraditionalcontrolmechanism.Itisastatementusedtoimmediatelyandunconditionallyjumptoanotherlineofcode.Tousegoto,youmustplacealabelatapointinyourprogram.Alabelconsistsofanamefollowedbya colon(:)onalinebyitself.Then,youcantype"goto label"atthedesiredpointinyourprogram.Thecodewillthencontinueexecutingbeginningwith label.Thislookslike:
M y L a b e l : / *s o m ec o d e* / g o t oM y L a b e l ;
Theabilitytotransfertheflowofcontrolenabledbygotosissopowerfulthat,inadditiontothesimpleif,allothercontrolconstructscanbewrittenusinggotosinstead.Here,wecanlet"S"and"T"beanyarbitrarystatements:
i f( ' ' c o n d ' ' ){ S ; }e l s e{ T ; } / *. . .* /
Thesamestatementcouldbeaccomplishedusingtwogotosandtwolabels:
i f( ' ' c o n d ' ' )g o t oL a b e l 1 ; T ; g o t oL a b e l 2 ; L a b e l 1 : S ; L a b e l 2 : / *. . .* /
Here,thefirstgotoisconditionalonthevalueof"cond".Thesecondgotoisunconditional.Wecanperformthesametranslationonaloop:
w h i l e( ' ' c o n d 1 ' ' ){ S ; i f( ' ' c o n d 2 ' ' )b r e a k ; T ; } / *. . .* /
Whichcanbewrittenas:
S t a r t : i f( ! ' ' c o n d 1 ' ' )g o t oE n d ; S ; i f( ' ' c o n d 2 ' ' )g o t oE n d ; T ; g o t oS t a r t ; E n d : / *. . .* /
Asthesecasesdemonstrate,oftenthestructureofwhatyourprogramisdoingcanusuallybeexpressedwithoutusinggotos.Undisciplineduseofgotoscancreateunreadable,unmaintainablecodewhenmoreidiomaticalternatives(suchasifelses,orfor loops)canbetterexpressyourstructure.Theoretically,thegotoconstructdoesnotever havetobeused,buttherearecaseswhenitcanincreasereadability,avoidcodeduplication,ormakecontrolvariablesunnecessary.Youshouldconsiderfirst masteringtheidiomaticsolutions,andusegotoonlywhennecessary.Keepinmindthatmany,ifnotmost,Cstyleguidelines strictlyforbiduseof goto,withtheonlycommonexceptionsbeingthefollowingexamples. Oneuseofgotoistobreakoutofadeeplynestedloop.Since breakwillnotwork(itcanonlyescapeoneloop), gotocanbeusedtojumpcompletelyoutsidetheloop.Breakingoutsideofdeeplynestedloopswithouttheuseofthegotoisalways possible,butofteninvolvesthecreationandtestingofextravariablesthatmaymaketheresultingcodefarlessreadablethanitwouldbewith goto.Theuseof gotomakesiteasytoundoactionsinanorderlyfashion,typicallytoavoidfailingtofree memorythathadbeenallocated. Anotheraccepteduseisthecreationofastatemachine.Thisisafairlyadvancedtopicthough,andnotcommonlyneeded.
Examples
en.wikibooks.org/wiki/C_Programming/Print_version 39/118
10/24/13
# i n c l u d e< e r r n o . h > # i n c l u d e< s t d i o . h > # i n c l u d e< s t d l i b . h > i n tm a i n ( v o i d ) { i n ty e a r s ; p r i n t f ( " E n t e ry o u ra g ei ny e a r s:" ) ; f f l u s h ( s t d o u t ) ; e r r n o=0 ; i f ( s c a n f ( " % d " ,& y e a r s )! =1| |e r r n o ) r e t u r nE X I T _ F A I L U R E ; p r i n t f ( " Y o u ra g ei nd a y si s% d \ n " ,y e a r s*3 6 5 ) ; r e t u r n0 ; }
Furtherreading
1. Severalprogrammersrecommend"usespacesforindentation.Donotusetabsinyourcode.Youshouldsetyoureditortoemitspaceswhenyouhitthetabkey."[1](http://googlestyleguide.googlecode.com/svn/trunk/cppguide.xml)[2] (http://www.jwz.org/doc/tabsvsspaces.html)Otherprogrammersdisagree.[3](http://diagrammesmodernes.blogspot.com/2006/04/tabversusspaces.html)[4](http://www.derkarl.org/why_to_tabs.html)Regardlessofwhetheryoupreferspacesor tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5](http://www.oualline.com/vimcook.html#drawing) 3. [http://lxr.linux.no/#linux+v2.6.31/Documentation/CodingStyleLinuxKernelcodingstandard 4. "CodingConventionsforC++andJava"(http://www.macadamian.com/index.php?option=com_content&task=view&id=34&Itemid=37)"alltheblockcommentsillustratedinthisdocumenthavenoprettystarsontherightsideoftheblockcomment. Thisdeliberatechoicewasmadebecausealigningthoseprettystarsisalargewasteoftimeanddiscouragesthemaintenanceofinlinecomments.", 5. wiki:BigBlocksOfAsterisks,"Codecraft"(http://books.google.com/books? id=i4zCzpkrt4sC&pg=PA82&lpg=PA82&dq=programming+comment+block+waste+time+lining+up&source=bl&ots=TUpTMIHBnh&sig=NeZm23WPmvnw2aKMnIRUeQoHmJg&hl=en&ei=pri3SevGIYGyNMn9jd4K&sa=X&oi=book_result&resnum=8&ct=result) byPeteGoodliffepage82,Falvotech"CProgrammingStyleGuide"(http://www.falvotech.com/content/publications/conventions/c/),FedoraDirectoryServerCodingStyle(http://directory.fedoraproject.org/wiki/Coding_Style)
Proceduresandfunctions
InCprogramming,allexecutablecoderesideswithina function.Afunctionisanamedblockofcodethatperformsataskandthenreturnscontroltoacaller.Notethatotherprogramminglanguagesmaydistinguishbetweena"function","subroutine", "subprogram","procedure",or"method"inC,theseareallfunctions. Afunctionisoftenexecuted(called)severaltimes,fromseveraldifferentplaces,duringasingleexecutionoftheprogram.Afterfinishingasubroutine,theprogramwillbranchback(return)tothepointafterthecall. Functionsareapowerfulprogrammingtool. Asabasicexample,supposeyouarewritingcodetoprintoutthefirst5squaresofnumbers,dosomeintermediateprocessing,thenprintthefirst5squaresagain.Wecouldwriteitlikethis:
# i n c l u d e< s t d i o . h > i n tm a i n ( v o i d ) { i n ti ; f o r ( i = 1 ;i< =5 ;i + + ) { p r i n t f ( " % d" ,i * i ) ; } f o r ( i = 1 ;i< =5 ;i + + ) { p r i n t f ( " % d" ,i * i ) ; } r e t u r n0 ; }
Wehavetowritethesamelooptwice.Wemaywanttosomehowputthiscodeinaseparateplaceandsimplyjumptothiscodewhenwewanttouseit.Thiswouldlooklike:
# i n c l u d e< s t d i o . h > v o i dP r i n t _ S q u a r e s ( v o i d ) { i n ti ; f o r ( i = 1 ;i< = 5 ;i + + ) { p r i n t f ( " % d" ,i * i ) ; } } i n tm a i n ( v o i d ) { P r i n t _ S q u a r e s ( ) ; P r i n t _ S q u a r e s ( ) ; r e t u r n0 ;
en.wikibooks.org/wiki/C_Programming/Print_version
40/118
10/24/13
}
Thisispreciselywhatfunctionsarefor.
Moreonfunctions
Afunctionislikeablackbox.Ittakesininput,doessomethingwithit,thenspitsoutananswer. Notethatafunctionmaynottakeanyinputsatall,oritmaynotreturnanythingatall.Intheaboveexample,ifweweretomakeafunctionofthatloop,wemaynotneedanyinputs,andwearen'treturninganythingatall(Textoutputdoesn'tcount whenwespeakof returningwemeantosaymeaningfuldatathattheprogramcanuse). Wehavesometerminologytorefertofunctions: Afunction,callit f ,thatusesanotherfunction g,issaidto call g.Forexample, f calls gtoprintthesquaresoftennumbers. Afunction'sinputsareknownasits arguments Afunction gthatgivessomekindofanswerbackto f issaidto returnthatanswer.Forexample, greturnsthesumofitsarguments.
WritingfunctionsinC
It'salwaysgoodtolearnbyexample.Let'swriteafunctionthatwillreturnthesquareofanumber.
i n ts q u a r e ( i n tx ) { i n ts q u a r e _ o f _ x ; s q u a r e _ o f _ x=x*x ; r e t u r ns q u a r e _ o f _ x ; }
Tounderstandhowtowritesuchafunctionlikethis,itmayhelptolookatwhatthisfunctiondoesasawhole.Ittakesinan i n t ,x,andsquaresit,storingitinthevariablesquare_of_x.Nowthisvalueisreturned. Thefirstintatthebeginningofthefunctiondeclarationisthetypeofdatathatthefunctionreturns.Inthiscasewhenwesquareanintegerwegetaninteger,andwearereturningthisinteger,andsowewrite i n t asthereturntype. Nextisthenameofthefunction.Itisgoodpracticetousemeaningfulanddescriptivenamesforfunctionsyoumaywrite.Itmayhelptonamethefunctionafterwhatitiswrittentodo.Inthiscasewenamethefunction"square",becausethat'swhatit doesitsquaresanumber. Nextisthefunction'sfirstandonlyargument,an i n t ,whichwillbereferredtointhefunctionasx.Thisisthefunction's input . Inbetweenthebracesistheactualgutsofthefunction.Itdeclaresanintegervariablecalledsquare_of_xthatwillbeusedtoholdthevalueofthesquareofx.Notethatthevariablesquare_of_xcan onlybeusedwithinthisfunction,andnotoutside. We'lllearnmoreaboutthissortofthinglater,andwewillseethatthispropertyisveryuseful. Wethenassignxmultipliedbyx,orxsquared,tothevariablesquare_of_x,whichiswhatthisfunctionisallabout.Followingthisisa r e t u r n statement.Wewanttoreturnthevalueofthesquareofx,sowemustsaythatthisfunctionreturnsthecontents ofthevariablesquare_of_x. Ourbracetoclose,andwehavefinishedthedeclaration. Writteninamoreconcisemanner,thiscodeperformsexactlythesamefunctionastheabove:
i n ts q u a r e ( i n tx ) { r e t u r nx*x ; }
Notethisshouldlookfamiliaryouhavebeenwritingfunctionsalready,infactmainisafunctionthatisalwayswritten.
Ingeneral
Ingeneral,ifwewanttodeclareafunction,wewrite
t y p en a m e ( t y p e 1a r g 1 ,t y p e 2a r g 2 ,. . . ) { / *c o d e* / }
en.wikibooks.org/wiki/C_Programming/Print_version
41/118
10/24/13
p r i n t f ( " H e l l o ! \ n ' ' ' " ) ; } }
Noticethisfunctiondoesn'ttakeanyinputs,butmerelyreturnsanumbercalculatedbythisfunction. Naturally,youcancombinebothvoidreturnandvoidinargumentstogethertogetavalidfunction,also.
Recursion
Here'sasimplefunctionthatdoesaninfiniteloop.Itprintsalineandcallsitself,whichagainprintsalineandcallsitselfagain,andthiscontinuesuntilthestackoverflowsandtheprogramcrashes.Afunctioncallingitselfiscalledrecursion,andnormally youwillhaveaconditionalthatwouldstoptherecursionafterasmall,finitenumberofsteps.
/ /d o n ' tr u nt h i s ! v o i di n f i n i t e _ r e c u r s i o n ( ) { p r i n t f ( " I n f i n i t el o o p ! \ n " ) ; i n f i n i t e _ r e c u r s i o n ( ) ; }
Asimplecheckcanbedonelikethis.Notethat++depthisusedsotheincrementwilltakeplacebeforethevalueispassedintothefunction.Alternativelyyoucanincrementonaseparatelinebeforetherecursioncall.Ifyousayprint_me(3,0)thefunction willprintthelineRecursion3times.
v o i dp r i n t _ m e ( i n tj ,i n td e p t h ) { i f ( d e p t h<j ){ p r i n t f ( " R e c u r s i o n !d e p t h=% dj=% d \ n " , d e p t h , j ) ;/ / jk e e p si t sv a l u e p r i n t _ m e ( j ,+ + d e p t h ) ; } }
Recursionismostoftenusedforjobssuchasdirectorytreescans,seekingfortheendofalinkedlist,parsingatreestructureinadatabaseandfactorisingnumbers(andfindingprimes)amongotherthings.
Staticfunctions
Ifafunctionistobecalledonlyfromwithinthefileinwhichitisdeclared,itisappropriatetodeclareitasastaticfunction.Whenafunctionisdeclaredstatic,thecompilerwillnowcompiletoanobjectfileinawaythatpreventsthefunctionfrombeing calledfromcodeinotherfiles.Example:
s t a t i ci n tc o m p a r e (i n ta ,i n tb) { r e t u r n( a + 4<b ) ?a:b ; }
UsingCfunctions
Wecannow writefunctions,buthowdoweusethem?Whenwewritemain,weplacethefunctionoutsidethebracesthatencompassmain. Whenwewanttousethatfunction,say,usingour c a l c u l a t e _ n u m b e r functionabove,wecanwritesomethinglike
f l o a tf ; f=c a l c u l a t e _ n u m b e r ( ) ;
Ifafunctiontakesinarguments,wecanwritesomethinglike
en.wikibooks.org/wiki/C_Programming/Print_version
42/118
10/24/13
i n ts q u a r e _ o f _ 1 0 ; s q u a r e _ o f _ 1 0=s q u a r e ( 1 0 ) ;
Ifafunctiondoesn'treturnanything,wecanjustsay
s a y _ h e l l o ( ) ;
sincewedon'tneedavariabletocatchitsreturnvalue.
FunctionsfromtheCStandardLibrary
WhiletheClanguagedoesn'titselfcontainfunctions,itisusuallylinkedwiththeCStandardLibrary.Tousethislibrary,youneedtoaddan#includedirectiveatthetopoftheCfile,whichmaybeoneofthefollowing:
< c o m p l e x . h >
Thefunctionsavailableare:
< a s s e r t . h > < l i m i t s . h > < s i g n a l . h > < s t d l i b . h >
assert(int)
(constantsonly)
intraise(intsig).This void*signal(intsig,void(*func)(int))
atof(char*),atoi(char*),atol(char*) strtod(char*str,char**endptr),strtol(char*str,char**endptr),strtoul(char*str,char**endptr) rand(),srand() malloc(size_t),calloc(size_telements,size_telementSize),realloc(void*,int) free(void*) exit(int),abort() atexit(void(*func)()) getenv system qsort(void*,size_tnumber,size_tsize,int(*sortfunc)(void*,void*)) abs,labs div,ldiv
< s t r i n g . h >
< c t y p e . h >
< l o c a l e . h >
< s t d a r g . h >
structlconv*localeconv(void) char*setlocale(int,constchar*)
memcpy,memmove memchr,memcmp,memset strcat,strncat,strchr,strrchr strcmp,strncmp,strccoll strcpy,strncpy strerror strlen strspn,strcspn strpbrk strstr strtok strxfrm time.h
errno.h
stddef.h
en.wikibooks.org/wiki/C_Programming/Print_version
43/118
10/24/13
fabs floor fmod frexp ldexp log,log10 modf pow sqrt
(errno)
offsetofmacro
float.h
setjmp.h fclose fopen,freopen remove rename rewind tmpfile clearerr feof,ferror fflush fgetpos,fsetpos fgetc,fputc fgets,fputs ftell,fseek
stdio.h fread,fwrite getc,putc getchar,putchar,fputchar gets,puts printf,vprintf fprintf,vfprintf sprintf,snprintf,vsprintf,vsnprintf perror scanf,vscanf fscanf,vfscanf sscanf,vsscanf setbuf,setvbuf tmpnam ungetc
(constants)
intsetjmp(jmp_bufenv) voidlongjmp(jmp_bufenv,intvalue)
printf fulllist(http://www.utas.edu.au/infosys/info/documentation/C/CStdLib.html#ctype.h)
Variablelengthargumentlists
Functionswithvariablelengthargumentlistsarefunctionsthatcantakeavaryingnumberofarguments.AnexampleintheCstandardlibraryisthe p r i n t f function,whichcantakeanynumberofargumentsdependingonhowtheprogrammerwantstouse it. Cprogrammersrarelyfindtheneedtowritenewfunctionswithvariablelengtharguments.Iftheywanttopassabunchofthingstoafunction,theytypicallydefineastructuretoholdallthosethingsperhapsalinkedlist,oranarrayandcallthat functionwiththedatainthearguments. However,youmayoccasionallyfindtheneedtowriteanewfunctionthatsupportsavariablelengthargumentlist.Tocreateafunctionthatcanacceptavariablelengthargumentlist,youmustfirstincludethestandardlibraryheader s t d a r g . h .Next,declare thefunctionasyouwouldnormally.Next,addasthelastargumentanellipsis("...").Thisindicatestothecompilerthatavariablelistofargumentsistofollow.Forexample,thefollowingfunctiondeclarationisforafunctionthatreturnstheaverageofa listofnumbers:
f l o a ta v e r a g e( i n tn _ a r g s ,. . . ) ;
en.wikibooks.org/wiki/C_Programming/Print_version
44/118
10/24/13
}
Bypopping n _ a r g s integersoffofthevariablelengthargumentlist,wecanmanagetofindtheaverageofthenumbers:
# i n c l u d e< s t d a r g . h > f l o a ta v e r a g e( i n tn _ a r g s ,. . . ) { v a _ l i s tm y L i s t ; v a _ s t a r t( m y L i s t ,n _ a r g s ) ; i n tn u m b e r s A d d e d=0 ; i n ts u m=0 ; w h i l e( n u m b e r s A d d e d<n _ a r g s ){ i n tn u m b e r=v a _ a r g( m y L i s t ,i n t ) ;/ /G e tn e x tn u m b e rf r o ml i s t s u m+ =n u m b e r ; n u m b e r s A d d e d+ =1 ; } v a _ e n d( m y L i s t ) ; f l o a ta v g=( f l o a t ) ( s u m )/( f l o a t ) ( n u m b e r s A d d e d ) ;/ /F i n dt h ea v e r a g e r e t u r na v g ; }
Preprocessor
PreprocessorsareawayofmakingtextprocessingwithyourCprogrambeforetheyareactuallycompiled.BeforetheactualcompilationofeveryCprogramitispassedthroughaPreprocessor.ThePreprocessorlooksthroughtheprogramtryingtofind outspecificinstructionscalledPreprocessordirectivesthatitcanunderstand.AllPreprocessordirectivesbeginwiththe#(hash)symbol.C++compilersusethesameCpreprocessor. [5] Thepreprocessorisapartofthecompilerwhichperformspreliminaryoperations(conditionallycompilingcode,includingfilesetc...)toyourcodebeforethecompilerseesit.Thesetransformationsarelexical,meaningthattheoutputofthepreprocessoris stilltext.
Directives
Directivesarespecialinstructionsdirectedtothepreprocessor(preprocessordirective)ortothecompiler(compilerdirective)onhowitshouldprocesspartorallofyoursourcecodeorsetsomeflagsonthefinalobjectandareusedtomakewritingsource codeeasier(moreportableforinstance)andtomakethesourcecodemoreunderstandable.Directivesarehandledbythepreprocessor,whichiseitheraseparateprograminvokedbythecompilerorpartofthecompileritself.
#include
Chassomefeaturesaspartofthelanguageandsomeothersaspartofa standardlibrary,whichisarepositoryofcodethatisavailablealongsideeverystandardconformantCcompiler.WhentheCcompilercompilesyourprogramitusuallyalsolinks itwiththestandardClibrary.Forexample,onencounteringa # i n c l u d e< s t d i o . h > directive,itreplacesthedirectivewiththecontentsofthe s t d i o . h headerfile. Whenyouusefeaturesfromthelibrary,Crequiresyouto declarewhatyouwouldbeusing.Thefirstlineintheprogramisa preprocessingdirectivewhichshouldlooklikethis:
# i n c l u d e< s t d i o . h >
TheabovelinecausestheCdeclarationswhichareinthe s t d i o . h headertobeincludedforuseinyourprogram.Usuallythisisimplementedbyjustinsertingintoyourprogramthecontentsofa headerfilecalled s t d i o . h ,locatedinasystemdependent location.Thelocationofsuchfilesmaybedescribedinyourcompiler'sdocumentation.AlistofstandardCheaderfilesislistedbelowintheHeaderstable. The s t d i o . h headercontainsvariousdeclarationsforinput/output(I/O)usinganabstractionofI/Omechanismscalled streams.Forexamplethereisanoutputstreamobjectcalled s t d o u t whichisusedtooutputtexttothestandardoutput,whichusually displaysthetextonthecomputerscreen.
en.wikibooks.org/wiki/C_Programming/Print_version
45/118
10/24/13
Ifusinganglebracketsliketheexampleabove,thepreprocessorisinstructedtosearchfortheincludefilealongthedevelopmentenvironmentpathforthestandardincludes.
# i n c l u d e" o t h e r . h "
NOTE:Youshouldcheckthedocumentationofthedevelopmentenvironmentyouareusingforanyvendorspecificimplementationsofthe # i n c l u d e directive.
Headers TheC90standardheaderslist:
< a s s e r t . h > < c t y p e . h > < e r r n o . h > < f l o a t . h > < l i m i t s . h >
< l o c a l e . h > < m a t h . h > < s e t j m p . h > < s i g n a l . h > < s t d a r g . h >
HeadersaddedsinceC90:
#pragma
The pragma(pragmaticinformation)directiveispartofthestandard,butthemeaningofanypragmadependsonthesoftwareimplementationofthestandardthatisused.The#pragmadirectiveprovidesawaytorequestspecialbehaviorfromthe compiler.Thisdirectiveismostusefulforprogramsthatareunusuallylargeorthatneedtotakeadvantageofthecapabilitiesofaparticularcompiler. Pragmasareusedwithinthesourceprogram.
# p r a g m at o k e n ( s )
NOTE:Othermethodsexisttodothisactionthatiscommonlyreferredasusing includeguards.
# d e f i n e
en.wikibooks.org/wiki/C_Programming/Print_version
46/118
10/24/13
The # d e f i n e directiveisusedtodefinevaluesormacrosthatareusedbythepreprocessortomanipulatetheprogramsourcecodebeforeitiscompiled.Becausepreprocessordefinitionsaresubstitutedbeforethecompileractsonthesourcecode,any errorsthatareintroducedby # d e f i n e aredifficulttotrace. Byconvention,valuesdefinedusing # d e f i n e arenamedinuppercase.Althoughdoingsoisnotarequirement,itisconsideredverybadpracticetodootherwise.Thisallowsthevaluestobeeasilyidentifiedwhenreadingthesourcecode. Today, # d e f i n e isprimarilyusedtohandlecompilerandplatformdifferences.E.g.,adefinemightholdaconstantwhichistheappropriateerrorcodeforasystemcall.Theuseof # d e f i n e shouldthusbelimitedunlessabsolutelynecessary t y p e d e f statements andconstantvariablescanoftenperformthesamefunctionsmoresafely. Anotherfeatureofthe # d e f i n e commandisthatitcantakearguments,makingitratherusefulasapseudofunctioncreator.Considerthefollowingcode:
# d e f i n eA B S O L U T E _ V A L U E (x)(( ( x )<0 )?( x ):( x )) . . . i n tx=1 ; w h i l e (A B S O L U T E _ V A L U E (x)){ . . . }
IfABSOLUTE_VALUE()werearealfunction'x'wouldnowhavethevalueof'9',butbecauseitwasanargumentinamacroitwasexpandedtwiceandthushasavalueof8.
Example: Toillustratethedangersofmacros,considerthisnaivemacro
# d e f i n eM A X ( a , b )a > b ? a : b
andthecode
i=M A X ( 2 , 3 ) + 5 ; j=M A X ( 3 , 2 ) + 5 ;
Takealookatthisandconsiderwhatthevalueafterexecutionmightbe.Thestatementsareturnedinto
i n ti=2 > 3 ? 2 : 3 + 5 ; i n tj=3 > 2 ? 3 : 2 + 5 ;
Thisworks,provided a , b havenosideeffects.Indeed,
i=2 ; j=3 ; k=M A X ( i + + ,j + + ) ;
hasnoneofthepitfallsabove,butwillnotworkwithalltypes.
en.wikibooks.org/wiki/C_Programming/Print_version
47/118
10/24/13
willmakethecompilerturnthiscommand
p u t s (a s _ s t r i n g (H e l l oW o r l d !));
into
p u t s (" H e l l oW o r l d ! ") ;
willmakethecompilerturn
p r i n t f (" % d " ,c o n c a t e n a t e (x ,y) ) ;
into
p r i n t f (" % d " ,x y ) ;
whichthemacroprocessorwillturninto
p u t s (" I ' me a t i n g"" f r u i t ""t o d a y . ")
whichinturnwillbeinterpretedbytheCparserasasinglestringconstant. Thefollowingtrickcanbeusedtoturnanumericconstantsintostringliterals
# d e f i n en u m 2 s t r ( x )s t r ( x )
en.wikibooks.org/wiki/C_Programming/Print_version
48/118
10/24/13
# d e f i n es t r ( x )# x # d e f i n eC O N S T2 3 p u t s ( n u m 2 s t r ( C O N S T ) ) ;
Thiswillgiveyouanicedebugmessageincludingthefileandthelinewherethemessagewasissued.IfDEBUGisnotdefinedhoweverthedebuggingmessagewillcompletelyvanishfromyourcode.Becarefulnottousethissortofconstructwith anythingthathassideeffects,sincethiscanleadtobugs,thatappearanddisappeardependingonthecompilationparameters.
macros
Macrosaren'ttypecheckedandsotheydonotevaluatearguments.Also,theydonotobeyscopeproperly,butsimplytakethestringpassedtothemandreplaceeachoccurrenceofthemacroargumentinthetextofthemacrowiththeactualstringfor thatparameter(thecodeisliterallycopiedintothelocationitwascalledfrom). Anexampleonhowtouseamacro:
# i n c l u d e< s t d i o . h > # d e f i n eS L I C E S8 # d e f i n eA D D ( x )(( x )/S L I C E S) i n tm a i n ( ) { i n ta=0 ,b=1 0 ,c=6 ; a=A D D ( b+c ) ; p r i n t f ( " % d \ n " ,a ) ; r e t u r n0 ; }
theresultof"a"shouldbe"2"(b+c=16>passedtoADD>16/SLICES>resultis"2")
#error
The #errordirectivehaltscompilation.Whenoneisencounteredthestandardspecifiesthatthecompilershouldemitadiagnosticcontainingtheremainingtokensinthedirective.Thisismostlyusedfordebuggingpurposes.
# e r r o rm e s s a g e
#warning
Manycompilerssupporta #warningdirective.Whenoneisencountered,thecompileremitsadiagnosticcontainingtheremainingtokensinthedirective. 1. warningmessage
#undef
The #undefdirectiveundefinesamacro.Theidentifierneednothavebeenpreviouslydefined.
#if,#else,#elif,#endif(conditionals)
en.wikibooks.org/wiki/C_Programming/Print_version
49/118
10/24/13
The #ifcommandcheckswhetheracontrollingconditionalexpressionevaluatestozeroornonzero,andexcludesorincludesablockofcoderespectively.Forexample:
# i f1 / *T h i sb l o c kw i l lb ei n c l u d e d* / # e n d i f # i f0 / *T h i sb l o c kw i l ln o tb ei n c l u d e d* / # e n d i f
#ifdef,#ifndef
The #ifdefcommandissimilarto # i f ,exceptthatthecodeblockfollowingitisselectedifamacronameisdefined.Inthisrespect,
# i f d e fN A M E
isequivalentto
# i fd e f i n e dN A M E
isequivalentto
# i f! d e f i n e dN A M E
UsefulPreprocessorMacrosforDebugging
ANSICdefinessomeusefulpreprocessormacrosandvariables, [7][8]alsocalled"magicconstants",include: __FILE__=>Thenameofthecurrentfile,asastringliteral __LINE__=>Currentlineofthesourcefile,asanumericliteral __DATE__=>Currentsystemdate,asastring __TIME__=>Currentsystemtime,asastring __TIMESTAMP__=>Dateandtime(nonstandard) __cplusplus=>undefinedwhenyourCcodeisbeingcompiledbyaCcompiler199711LwhenyourCcodeisbeingcompiledbyaC++compilercompliantwith1998C++standard. __func__=>Currentfunctionnameofthesourcefile,asastring(partofC99) __PRETTY_FUNCTION__=>"decorated"Currentfunctionnameofthesourcefile,asastring(inGCCnonstandard) Compiletimeassertions
en.wikibooks.org/wiki/C_Programming/Print_version
50/118
10/24/13
Somepeople[9]defineapreprocessormacrotoallowcompiletimeassertions,somethinglike:
# d e f i n eC O M P I L E _ T I M E _ A S S E R T ( p r e d )s w i t c h ( 0 ) { c a s e0 : c a s ep r e d : ; } C O M P I L E _ T I M E _ A S S E R T (B O O L E A NC O N D I T I O N) ;
The s t a t i c _ a s s e r t . h p p Boostlibrarydefinesasimilarmacro.Somecompilersdefinea s t a t i c _ a s s e r t keywordusedinthesameway. [10] Suchcompiletimeassertionscanhelpyoudebugfasterthanusingonlyruntimeassert()statements,becausethecompiletimeassertionsarealltestedatcompiletime,whileitispossiblethatatestrunofaprogrammayfailtoexercisesomeruntime assert()statements. XMacros OnelittleknownusagepatternoftheCpreprocessorisknownas"XMacros". [11][12][13][14]AnXMacroisaheaderfileormacro.Commonlytheseusetheextension".def"insteadofthetraditional".h".Thisfilecontainsalistofsimilarmacrocalls,which canbereferredtoas"componentmacros".Theincludefileisthenreferencedrepeatedlyinthefollowingpattern.Here,theincludefileis"xmacro.def"anditcontainsalistofcomponentmacrosofthestyle"foo(x,y,z)".
# d e f i n ef o o ( x ,y ,z )d o S o m e t h i n g W i t h ( x ,y ,z ) ; # i n c l u d e" x m a c r o . d e f " # u n d e ff o o # d e f i n ef o o ( x ,y ,z )d o S o m e t h i n g E l s e W i t h ( x ,y ,z ) ; # i n c l u d e" x m a c r o . d e f " # u n d e ff o o ( e t c . . . )
File star_table.c:
t y p e d e fs t r u c t{ # d e f i n eE X P A N D _ E X P A N D _ S T A R _ M E M B E R ( m e m b e r ,t y p e )t y p em e m b e r ; # i n c l u d e" s t a r . d e f " }s t a r S t r u c t ; v o i ds e r i a l i z e _ s t a r ( c o n s ts t a r S t r u c t* c o n s ts t a r ,u n s i g n e dc h a r* b u f f e r ){ # d e f i n eE X P A N D _ E X P A N D _ S T A R _ M E M B E R ( m e m b e r ,t y p e )\ m e m c p y ( b u f f e r ,& ( s t a r > m e m b e r ) ,s i z e o f ( s t a r > m e m b e r ) ) ;\ b u f f e r+ =s i z e o f ( s t a r > m e m b e r ) ; # i n c l u d e" s t a r . d e f " } v o i dd e s e r i a l i z e _ s t a r ( s t a r S t r u c t* c o n s ts t a r ,c o n s tu n s i g n e dc h a r* b u f f e r ){ # d e f i n eE X P A N D _ E X P A N D _ S T A R _ M E M B E R ( m e m b e r ,t y p e )\ m e m c p y ( & ( s t a r > m e m b e r ) ,b u f f e r ,s i z e o f ( s t a r > m e m b e r ) ) ;\ b u f f e r+ =s i z e o f ( s t a r > m e m b e r ) ; # i n c l u d e" s t a r . d e f " }
en.wikibooks.org/wiki/C_Programming/Print_version
51/118
10/24/13
# i n c l u d e" s t a r . d e f " }
Notethatinthisexampleyoucanalsoavoidthecreationofseparatehandlerfunctionsforeachdatatypeinthisexamplebydefiningtheprintformatforeachsupportedtype,withtheadditionalbenefitofreducingtheexpansioncodeproducedbythis headerfile:
# d e f i n eF O R M A T _ ( t y p e )F O R M A T _ # # t y p e # d e f i n eF O R M A T _ i n t " % d " # d e f i n eF O R M A T _ d o u b l e" % g " v o i dp r i n t _ s t a r ( c o n s ts t a r S t r u c t* c o n s ts t a r ){ / *F O R M A T _ ( t y p e )w i l lb er e p l a c e dw i t hF O R M A T _ i n to rF O R M A T _ d o u b l e* / # d e f i n eE X P A N D _ E X P A N D _ S T A R _ M E M B E R ( m e m b e r ,t y p e )\ p r i n t f ( " % s :"F O R M A T _ ( t y p e )" \ n " ,# m e m b e r ,s t a r > m e m b e r ) ; # i n c l u d e" s t a r . d e f " }
andtheprinthandlercouldbeaddedaswellas:
# d e f i n ep r i n t _ i n t ( v a l ) p r i n t f ( " % d " ,v a l ) # d e f i n ep r i n t _ d o u b l e ( v a l )p r i n t f ( " % g " ,v a l ) v o i dp r i n t _ s t a r ( c o n s ts t a r S t r u c t* c o n s ts t a r ){ / *p r i n t _ # # t y p ew i l lb er e p l a c e dw i t hp r i n t _ i n to rp r i n t _ d o u b l e* / # d e f i n eE X P A N D _ S T A R _ M E M B E R ( m e m b e r ,t y p e )\ p r i n t f ( " % s :" ,# m e m b e r ) ;\ p r i n t _ # # t y p e ( s t a r > m e m b e r ) ;\ p r i n t f ( " \ n " ) ; E X P A N D _ S T A R # u n d e fE X P A N D _ S T A R _ M E M B E R }
oras:
# d e f i n eF O R M A T _ ( t y p e )F O R M A T _ # # t y p e # d e f i n eF O R M A T _ i n t " % d " # d e f i n eF O R M A T _ d o u b l e" % g " v o i dp r i n t _ s t a r ( c o n s ts t a r S t r u c t* c o n s ts t a r ){ / *F O R M A T _ ( t y p e )w i l lb er e p l a c e dw i t hF O R M A T _ i n to rF O R M A T _ d o u b l e* / # d e f i n eE X P A N D _ S T A R _ M E M B E R ( m e m b e r ,t y p e )\ p r i n t f ( " % s :"F O R M A T _ ( t y p e )" \ n " ,# m e m b e r ,s t a r > m e m b e r ) ; E X P A N D _ S T A R # u n d e fE X P A N D _ S T A R _ M E M B E R
en.wikibooks.org/wiki/C_Programming/Print_version
52/118
10/24/13
}
Thisapproachcanbedangerousinthattheentiremacrosetisalwaysinterpretedasifitwasonasinglesourceline,whichcouldencountercompilerlimitswithcomplexcomponentmacrosand/orlongmemberlists. ThistechniquewasreportedbyLarsWirzenius[15]inawebpagedatedJanuary17,2000,inwhichhegivescredittoKennethOksanenfor"refininganddeveloping"thetechniquepriorto1997.Theotherreferencesdescribeitasamethodfromatleasta decadebeforetheturnofthecentury. 1. Severalprogrammersrecommend"usespacesforindentation.Donotusetabsinyourcode.Youshouldsetyoureditortoemitspaceswhenyouhitthetabkey."[1](http://googlestyleguide.googlecode.com/svn/trunk/cppguide.xml)[2] (http://www.jwz.org/doc/tabsvsspaces.html)Otherprogrammersdisagree.[3](http://diagrammesmodernes.blogspot.com/2006/04/tabversusspaces.html)[4](http://www.derkarl.org/why_to_tabs.html)Regardlessofwhetheryoupreferspacesor tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5](http://www.oualline.com/vimcook.html#drawing) 3. [http://lxr.linux.no/#linux+v2.6.31/Documentation/CodingStyleLinuxKernelcodingstandard 4. "CodingConventionsforC++andJava"(http://www.macadamian.com/index.php?option=com_content&task=view&id=34&Itemid=37)"alltheblockcommentsillustratedinthisdocumenthavenoprettystarsontherightsideoftheblockcomment. Thisdeliberatechoicewasmadebecausealigningthoseprettystarsisalargewasteoftimeanddiscouragesthemaintenanceofinlinecomments.", 5. wiki:BigBlocksOfAsterisks,"Codecraft"(http://books.google.com/books? id=i4zCzpkrt4sC&pg=PA82&lpg=PA82&dq=programming+comment+block+waste+time+lining+up&source=bl&ots=TUpTMIHBnh&sig=NeZm23WPmvnw2aKMnIRUeQoHmJg&hl=en&ei=pri3SevGIYGyNMn9jd4K&sa=X&oi=book_result&resnum=8&ct=result) byPeteGoodliffepage82,Falvotech"CProgrammingStyleGuide"(http://www.falvotech.com/content/publications/conventions/c/),FedoraDirectoryServerCodingStyle(http://directory.fedoraproject.org/wiki/Coding_Style)
Libraries
A libraryinCisagroupoffunctionsanddeclarations,exposedforusebyotherprograms.Thelibrarythereforeconsistsofan interfaceexpressedina . h file(namedthe"header")andan implementationexpressedina . c file.This . c filemightbe precompiledorotherwiseinaccessible,oritmightbeavailabletotheprogrammer.(Note:LibrariesmaycallfunctionsinotherlibrariessuchastheStandardCormathlibrariestodovarioustasks.) Theformatofalibraryvarieswiththeoperatingsystemandcompileroneisusing.Forexample,intheUnixandLinuxoperatingsystems,alibraryconsistsofoneormore objectfiles,whichconsistofobjectcodethatisusuallytheoutputofacompiler(if thesourcelanguageisCorsomethingsimilar)oranassembler(ifthesourcelanguageisassemblylanguage).Theseobjectfilesarethenturnedintoalibraryintheformofanarchivebythe ararchiver(aprogramthattakesfilesandstoresthemina biggerfilewithoutregardtocompression).Thefilenameforthelibraryusuallystartswith"lib"andendswith".a"e.g.the libc.afilecontainstheStandardClibraryandthe"libm.a"themathematicsroutines,whichthelinkerwouldthenlinkin.Other
en.wikibooks.org/wiki/C_Programming/Print_version
53/118
10/24/13
operatingsystemssuchasMicrosoftWindowsusea".lib"extensionforlibrariesandan".obj"extensionforobjectfiles. We'regoingtouseasanexampleafunctiontoparseargumentsfromthecommandline.Argumentsonthecommandlinecouldbebythemselves:
i
haveanoptionalargumentthatisconcatenated(http://en.wikipedia.org/wiki/Concatenate)totheletter:
i o p t a r g
orhavetheargumentinaseparateargvelement:
io p t a r g
Inordertoparseallthesetypesofarguments,wehavewrittenthefollowing"getopt.c"file:
# i n c l u d e< s t d i o . h > # i n c l u d e< s t r i n g . h > # i n c l u d e" g e t o p t . h " / *v a r i a b l e s* / i n to p t e r r=1 ; i n to p t i n d=1 ; i n to p t o p t ; c h a r* o p t a r g ; / *f o rf p r i n t f ( )a n dE O F* / / *f o rs t r c h r ( )* / / *c o n s i s t e n c yc h e c k* / / *g e t o p tp r i n t se r r o r si ft h i si so n* / / *t o k e np o i n t e r* / / *o p t i o nc h a r a c t e rp a s s e db a c kt ou s e r* / / *f l a ga r g u m e n t( o rv a l u e )* /
/ *f u n c t i o n* / / *r e t u r no p t i o nc h a r a c t e r ,E O Fi fn om o r eo r?i fp r o b l e m . T h ea r g u m e n t st ot h ef u n c t i o n : a r g c ,a r g v-t h ea r g u m e n t st ot h em a i n ( )f u n c t i o n .A na r g u m e n to f" " s t o p st h ep r o c e s s i n g . o p t s-as t r i n gc o n t a i n i n gt h ev a l i do p t i o nc h a r a c t e r s . a no p t i o nc h a r a c t e rf o l l o w e db yac o l o n( : )i n d i c a t e st h a t t h eo p t i o nh a sar e q u i r e da r g u m e n t . * / i n t g e t o p t( i n ta r g c ,c h a r* * a r g v ,c h a r* o p t s ) { s t a t i ci n ts p=1 ; / *c h a r a c t e ri n d e xi n t oc u r r e n tt o k e n* / r e g i s t e rc h a r* c p ; / *p o i n t e ri n t oc u r r e n tt o k e n* / i f( s p= =1 ) { / *c h e c kf o rm o r ef l a g l i k et o k e n s* / i f( o p t i n d> =a r g c| |a r g v [ o p t i n d ] [ 0 ]! =' '| |a r g v [ o p t i n d ] [ 1 ]= =' \ 0 ' ) r e t u r nE O F ; e l s ei f( s t r c m p( a r g v [ o p t i n d ] ," " )= =0 ) { o p t i n d + + ; r e t u r nE O F ; } } o p t o p t=a r g v [ o p t i n d ] [ s p ] ; i f( o p t o p t= =' : '| |( c p=s t r c h r( o p t s ,o p t o p t ) )= =N U L L ) { i f( o p t e r r ) f p r i n t f( s t d e r r ," % s :i n v a l i do p t i o n-' % c ' \ n " ,a r g v [ 0 ] ,o p t o p t ) ; / *i fn oc h a r a c t e r sl e f ti nt h i st o k e n ,m o v et on e x tt o k e n* / i f( a r g v [ o p t i n d ] [ + + s p ]= =' \ 0 ' ) { o p t i n d + + ; s p=1 ; } r e t u r n' ? ' ; } i f( * + + c p= =' : ' ) { / *i fav a l u ei se x p e c t e d ,g e ti t* / i f( a r g v [ o p t i n d ] [ s p+1 ]! =' \ 0 ' ) / *f l a gv a l u ei sr e s to fc u r r e n tt o k e n* / o p t a r g=a r g v [ o p t i n d + + ]+( s p+1 ) ; e l s ei f( + + o p t i n d> =a r g c ) { i f( o p t e r r ) f p r i n t f( s t d e r r ," % s :o p t i o nr e q u i r e sa na r g u m e n t-' % c ' \ n " , a r g v [ 0 ] ,o p t o p t ) ; s p=1 ;
en.wikibooks.org/wiki/C_Programming/Print_version
54/118
10/24/13
r e t u r n' ? ' ; } e l s e / *f l a gv a l u ei sn e x tt o k e n* / o p t a r g=a r g v [ o p t i n d + + ] ; s p=1 ; } e l s e { / *s e tu pt ol o o ka tn e x tc h a ri nt o k e n ,n e x tt i m e* / i f( a r g v [ o p t i n d ] [ + + s p ]= =' \ 0 ' ) { / *n om o r ei nc u r r e n tt o k e n ,s os e t u pn e x tt o k e n* / s p=1 ; o p t i n d + + ; } o p t a r g=0 ; } r e t u r no p t o p t ; } / *E N DO FF I L E* /
Theinterfacewouldbethefollowing"getopt.h"file:
# i f n d e fG E T O P T _ H # d e f i n eG E T O P T _ H / *e x p o r t e dv a r i a b l e s* / e x t e r ni n to p t e r r ,o p t i n d ,o p t o p t ; e x t e r nc h a r* o p t a r g ; / *e x p o r t e df u n c t i o n* / i n tg e t o p t ( i n t ,c h a r* * ,c h a r* ) ; # e n d i f / *E N DO FF I L E* /
Ataminimum,aprogrammerhastheinterfacefiletofigureouthowtousealibrary,although,ingeneral,thelibraryprogrammeralsowrotedocumentationonhowtousethelibrary.Intheabovecase,thedocumentationshouldsaythattheprovided arguments * * a r g v and * o p t s bothshouldn'tbenullpointers(orwhywouldyoubeusingthe g e t o p t functionanyway?).Specifically,ittypicallystateswhateachparameterisforandwhatreturnvaluescanbeexpectedinwhichconditions.Programmersthat usealibrary,arenormallynotinterestedintheimplementationofthelibraryunlesstheimplementationhasabug,inwhichcasehewouldwanttocomplainsomehow. Boththeimplementationofthegetoptslibrary,andprogramsthatusethelibraryshouldstate # i n c l u d e" g e t o p t . h " ,inordertorefertothecorrespondinginterface.Nowthelibraryis"linked"totheprogramtheonethatcontainsthemain()function.The programmayrefertodozensofinterfaces. Insomecases,justplacing # i n c l u d e" g e t o p t . h " mayappearcorrectbutwillstillfailtolinkproperly.Thisindicatesthatthelibraryisnotinstalledcorrectly,ortheremaybesomeadditionalconfigurationrequired.Youwillhavetocheckeitherthecompiler's documentationorlibrary'sdocumentationonhowtoresolvethisissue.
Whattoputinheaderfiles
Asageneralrule,headerscontainanythingthatshouldbeexported,or"seen"bytheothermodulesinaprogram.Thisincludesmacrodefinitions(preprocessor # d e f i n e s)structure,union,andenumerationdeclarationstypedefdeclarationsexternal functiondeclarationsandglobalvariabledeclarations.Intheabove g e t o p t . h examplefile,onefunctiondeclaration(g e t o p t )andfourglobalvariables(o p t i n d , o p t o p t , o p t a r g ,and o p t e r r )aredefined. The # i f n d e fG E T O P T _ H / # d e f i n eG E T O P T _ H trickiscolloquiallycalled includeguards.Thisisusedsothatifthe g e t o p t . h filewereincludedmorethanonceinatranslationunit,theunitwouldonlyseethecontentsonce.
Furtherreading
CFAQ:"I'mwonderingwhattoputin.cfilesandwhattoputin.hfiles.(Whatdoes".h"mean,anyway?)"(http://cfaq.com/cpp/hfiles.html) PIClistthread:"GlobalvariablesinprojectswithmanyCfiles."(http://www.piclist.com/techref/postbot.asp?by=time&id=piclist\2007\10\25\073430a&tgt=post)
Standardlibraries
The Cstandardlibraryisastandardizedcollectionofheaderfilesandlibraryroutinesusedtoimplementcommonoperations,suchasinput/outputandcharacterstringhandling.Unlikeotherlanguages(suchasCOBOL,Fortran,andPL/I)Cdoesnot includebuiltinkeywordsforthesetasks,sonearlyallCprogramsrelyonthestandardlibrarytofunction.
History
TheCprogramminglanguagepreviouslydidnotprovideanyelementaryfunctionalities,suchasI/Ooperations.Overtime,usercommunitiesofCsharedideasandimplementationstoprovidethatfunctionality.Theseideasbecamecommon,andwere eventuallyincorporatedintothedefinitionofthestandardizedCprogramminglanguage.Thesearenowcalledthe Cstandardlibraries. BothUnixandCwerecreatedatAT&T'sBellLaboratoriesinthelate1960sandearly1970s.Duringthe1970stheCprogramminglanguagebecameincreasinglypopular,withmanyuniversitiesandorganizationsbeginningtocreatetheirownvariationsof thelanguagefortheirownprojects.Bythestartofthe1980scompatibilityproblemsbetweenthevariousCimplementationsbecameapparent.In1983theAmericanNationalStandardsInstitute(ANSI)formedacommitteetoestablishastandard specificationofCknownas"ANSIC".Thisworkculminatedinthecreationofthesocalled C89standardin1989.Partoftheresultingstandardwasasetofsoftwarelibrariescalledthe ANSICstandardlibrary. LaterrevisionsoftheCstandardhaveaddedseveralnewrequiredheaderfilestothelibrary.Supportforthesenewextensionsvariesbetweenimplementations.
en.wikibooks.org/wiki/C_Programming/Print_version
55/118
10/24/13
Theheaders <iso646.h>, <wchar.h>,and <wctype.h>wereaddedwithNormativeAddendum1(hereafterabbreviatedas NA1),anadditiontotheCStandardratifiedin1995. Theheaders <complex.h>, <fenv.h>, <inttypes.h>, <stdbool.h>, <stdint.h>,and <tgmath.h>wereaddedwith C99,arevisiontotheCStandardpublishedin1999.
Design
Thedeclarationofeachfunctioniskeptinaheaderfile,whiletheactualimplementationoffunctionsareseparatedintoalibraryfile.Thenamingandscopeofheadershavebecomecommonbuttheorganizationoflibrariesstillremainsdiverse.The standardlibraryisusuallyshippedalongwithacompiler.SinceCcompilersoftenprovideextrafunctionalitiesthatarenotspecifiedinANSIC,astandardlibrarywithaparticularcompilerismostlyincompatiblewithstandardlibrariesofothercompilers. MuchoftheCstandardlibraryhasbeenshowntohavebeenwelldesigned.Afewparts,withthebenefitofhindsight,areregardedasmistakes.Thestringinputfunctions g e t s ( ) (andtheuseof s c a n f ( ) toreadstringinput)arethesourceofmanybuffer overflows,andmostprogrammingguidesrecommendavoidingthisusage.Anotheroddityis s t r t o k ( ) ,afunctionthatisdesignedasaprimitivelexicalanalyserbutishighly"fragile"anddifficulttouse.
ANSIStandard
TheANSICstandardlibraryconsistsof24Cheaderfileswhichcanbeincludedintoaprogrammer'sprojectwithasingledirective.Eachheaderfilecontainsoneormorefunctiondeclarations,datatypedefinitionsandmacros.Thecontentsofthese headerfilesfollows. Incomparisontosomeotherlanguages(forexampleJava)thestandardlibraryisminuscule.Thelibraryprovidesabasicsetofmathematicalfunctions,stringmanipulation,typeconversions,andfileandconsolebasedI/O.Itdoesnotincludeastandard setof"containertypes"liketheC++StandardTemplateLibrary,letalonethecompletegraphicaluserinterface(GUI)toolkits,networkingtools,andprofusionofotherfunctionalitythatJavaprovidesasstandard.Themainadvantageofthesmallstandard libraryisthatprovidingaworkingANSICenvironmentismucheasierthanitiswithotherlanguages,andconsequentlyportingCtoanewplatformisrelativelyeasy. Manyotherlibrarieshavebeendevelopedtosupplyequivalentfunctionalitytothatprovidedbyotherlanguagesintheirstandardlibrary.Forinstance,theGNOMEdesktopenvironmentprojecthasdevelopedtheGTK+graphicstoolkitandGLib,alibrary ofcontainerdatastructures,andtherearemanyotherwellknownexamples.Thevarietyoflibrariesavailablehasmeantthatsomesuperiortoolkitshaveproventhemselvesthroughhistory.Theconsiderabledownsideisthattheyoftendonotwork particularlywelltogether,programmersareoftenfamiliarwithdifferentsetsoflibraries,andadifferentsetofthemmaybeavailableonanyparticularplatform.
ANSIClibraryheaderfiles
<assert.h> Containstheassertmacro,usedtoassistwithdetectinglogicalerrorsandothertypesofbugindebuggingversionsofaprogram.
<complex.h> Asetoffunctionsformanipulatingcomplexnumbers.(Newwith C99) <ctype.h> <errno.h> <fenv.h> <float.h> Thisheaderfilecontainsfunctionsusedtoclassifycharactersbytheirtypesortoconvertbetweenupperandlowercaseinawaythatisindependentoftheusedcharacterset(typicallyASCIIoroneofitsextensions,although implementationsutilizingEBCDICarealsoknown). Fortestingerrorcodesreportedbylibraryfunctions. Forcontrollingfloatingpointenvironment.(Newwith C99) Containsdefinedconstantsspecifyingtheimplementationspecificpropertiesofthefloatingpointlibrary,suchastheminimumdifferencebetweentwodifferentfloatingpointnumbers(_EPSILON),themaximumnumberofdigitsof accuracy(_DIG)andtherangeofnumberswhichcanberepresented(_MIN,_MAX).
<inttypes.h> Forpreciseconversionbetweenintegertypes.(Newwith C99) <iso646.h> <limits.h> <locale.h> <math.h> <setjmp.h> <signal.h> <stdarg.h> ForprogramminginISO646variantcharactersets.(Newwith NA1) Containsdefinedconstantsspecifyingtheimplementationspecificpropertiesoftheintegertypes,suchastherangeofnumberswhichcanberepresented(_MIN,_MAX). Forsetlocale()andrelatedconstants.Thisisusedtochooseanappropriatelocale. Forcomputingcommonmathematicalfunctions seeFurthermathorC++Programming/Code/StandardCLibrary/Mathfordetails. setjmpandlongjmp,whichareusedfornonlocalexits Forcontrollingvariousexceptionalconditions Foraccessingavaryingnumberofargumentspassedtofunctions.
<stdbool.h> Forabooleandatatype.(Newwith C99) <stdint.h> <stddef.h> <stdio.h> <stdlib.h> <string.h> <tgmath.h> Fordefiningvariousintegertypes.(Newwith C99) Fordefiningseveralusefultypesandmacros. ProvidesthecoreinputandoutputcapabilitiesoftheClanguage.Thisfileincludesthevenerable p r i n t f function. Forperformingavarietyofoperations,includingconversion,pseudorandomnumbers,memoryallocation,processcontrol,environment,signalling,searching,andsorting. Formanipulatingseveralkindsofstrings. Fortypegenericmathematicalfunctions.(Newwith C99) Forconvertingbetweenvarioustimeanddateformats. <wchar.h> <wctype.h> Formanipulatingwidestreamsandseveralkindsofstringsusingwidecharacterskeytosupportingarangeoflanguages.(Newwith NA1) Forclassifyingwidecharacters.(Newwith NA1)
en.wikibooks.org/wiki/C_Programming/Print_version
56/118
10/24/13
Commonsupportlibraries
Whilenotstandardized,Cprogramsmaydependonaruntimelibraryofroutineswhichcontaincodethecompilerusesatruntime.Thecodethatinitializestheprocessfortheoperatingsystem,forexample,beforecalling m a i n ( ) ,isimplementedintheC RunTimeLibraryforagivenvendor'scompiler.TheRunTimeLibrarycodemighthelpwithotherlanguagefeatureimplementations,likehandlinguncaughtexceptionsorimplementingfloatingpointcode. TheCstandardlibraryonlydocumentsthatthespecificroutinesmentionedinthisarticleareavailable,andhowtheybehave.Becausethecompilerimplementationmightdependontheseadditionalimplementationlevelfunctionstobeavailable,itis likelythevendorspecificroutinesarepackagedwiththeCStandardLibraryinthesamemodule,becausethey'rebothlikelytobeneededbyanyprogrambuiltwiththeirtoolset. ThoughoftenconfusedwiththeCStandardLibrarybecauseofthispackaging,theCRuntimeLibraryisnotastandardizedpartofthelanguageandisvendorspecific.
Compilerbuiltinfunctions
Somecompilers(forexample,GCC)providebuiltinversionsofmanyofthefunctionsintheCstandardlibrarythatis,theimplementationsofthefunctionsarewrittenintothecompiledobjectfile,andtheprogramcallsthebuiltinversionsinsteadofthe functionsintheClibrarysharedobjectfile.Thisreducesfunctioncalloverhead,especiallyiffunctioncallsarereplacedwithinlinevariants,andallowsotherformsofoptimization(asthecompilerknowsthecontrolflowcharacteristicsofthebuiltin variants),butmaycauseconfusionwhendebugging(forexample,thebuiltinversionscannotbereplacedwithinstrumentedvariants).
POSIXstandardlibrary
POSIX,(alongwiththeSingleUnixSpecification),specifiesanumberofroutinesthatshouldbeavailableoverandabovethoseintheCstandardlibrarypropertheseareoftenimplementedalongsidetheCstandardlibraryfunctionality,withvarying degreesofcloseness.Forexample,glibcimplementsfunctionssuchasforkwithinlibc.so,butbeforeNPTLwasmergedintoglibcitconstitutedaseparatelibrarywithitsownlinkerflag.Often,thisPOSIXspecifiedfunctionalitywillberegardedaspartof thelibrarytheClibrarypropermaybeidentifiedastheANSIorISOClibrary.
FileIO
Introduction
The s t d i o . h headerdeclaresabroadassortmentoffunctionsthatperforminputandoutputtofilesanddevicessuchastheconsole.ItwasoneoftheearliestheaderstoappearintheClibrary.Itdeclaresmorefunctionsthananyotherstandardheaderand alsorequiresmoreexplanationbecauseofthecomplexmachinerythatunderliesthefunctions. Thedeviceindependentmodelofinputandoutputhasseendramaticimprovementovertheyearsandhasreceivedlittlerecognitionforitssuccess.FORTRANIIwastoutedasamachineindependentlanguageinthe1960s,yetitwasessentially impossibletomoveaFORTRANprogrambetweenarchitectureswithoutsomechange.InFORTRANII,younamedthedeviceyouweretalkingtorightintheFORTRANstatementinthemiddleofyourFORTRANcode.So,yousaid R E A DI N P U TT A P E5 ona tapeorientedIBM7090but R E A DC A R D toreadacardimageonothermachines.FORTRANIVhadmoregeneric R E A D and W R I T E statements,specifyinga logicalunitnumber(LUN)insteadofthedevicename.TheeraofdeviceindependentI/Ohaddawned. Peripheraldevicessuchasprintersstillhadfairlystrongnotionsaboutwhattheywereaskedtodo.Andthen, peripheralinterchangeutilitieswereinventedtohandlebizarredevices.Whencathoderaytubescameontothescene,eachmanufacturerof consolessolvedproblemssuchasconsolecursormovementinanindependentmanner,causingfurtherheadaches. ItwasintothisatmospherethatUnixwasborn.KenThompsonandDennisRitchie,thedevelopersofUnix,deservecreditforpackinganynumberofbrightideasintotheoperatingsystem.Theirapproachtodeviceindependencewasoneofthebrightest. TheANSIC < s t d i o . h > libraryisbasedontheoriginalUnixfileI/Oprimitivesbutcastsawidernettoaccommodatetheleastcommondenominatoracrossvariedsystems.
Streams
Inputandoutput,whethertoorfromphysicaldevicessuchasterminalsandtapedrives,orwhethertoorfromfilessupportedonstructuredstoragedevices,aremappedintologicaldatastreams,whosepropertiesaremoreuniformthantheirvarious inputsandoutputs.Twoformsofmappingaresupported:textstreamsandbinarystreams. Atextstreamconsistsofoneormorelines.Alineinatextstreamconsistsofzeroormorecharactersplusaterminatingnewlinecharacter.(Theonlyexceptionisthatinsomeimplementationsthelastlineofafiledoesnotrequireaterminatingnewline character.)Unixadoptedastandardinternalformatforalltextstreams.Eachlineoftextisterminatedbyanewlinecharacter.That'swhatanyprogramexpectswhenitreadstext,andthat'swhatanyprogramproduceswhenitwritestext.(Thisisthe mostbasicconvention,andifitdoesn'tmeettheneedsofatextorientedperipheralattachedtoaUnixmachine,thenthefixupoccursoutattheedgesofthesystem.Nothinginbetweenneedstochange.)Thestringofcharactersthatgointo,orcome outofatextstreammayhavetobemodifiedtoconformtospecificconventions.Thisresultsinapossibledifferencebetweenthedatathatgointoatextstreamandthedatathatcomeout.Forinstance,insomeimplementationswhenaspacecharacter precedesanewlinecharacterintheinput,thespacecharactergetsremovedoutoftheoutput.Ingeneral,whenthedataonlyconsistsofprintablecharactersandcontrolcharacterslikehorizontaltabandnewline,theinputandoutputofatextstreamare equal. Comparedtoatextstream,abinarystreamisprettystraightforward.Abinarystreamisanorderedsequenceofcharactersthatcantransparentlyrecordinternaldata.Datawrittentoabinarystreamshallalwaysequalthedatathatgetsreadoutunder thesameimplementation.Binarystreams,however,mayhaveanimplementationdefinednumberofnullcharactersappendedtotheendofthestream.Therearenofurtherconventionswhichneedtobeconsidered. NothinginUnixpreventstheprogramfromwritingarbitrary8bitbinarycodestoanyopenfile,orreadingthembackunchangedfromanadequaterepository.Thus,Unixobliteratedthelongstandingdistinctionbetweentextstreamsandbinarystreams.
StandardStreams
WhenaCprogramstartsitsexecutiontheprogramautomaticallyopensthreestandardstreamsnamed s t d i n , s t d o u t ,and s t d e r r .TheseareattachedforeveryCprogram. Thefirststandardstreamisusedforinputbufferingandtheothertwoareusedforoutput.Thesestreamsaresequencesofbytes. Considerthefollowingprogram:
/ *Ae x a m p l ep r o g r a m .* / i n tm a i n ( ) { i n tv a r ; s c a n f( " % d " ,& v a r ) ;/ *u s es t d i nf o rs c a n n i n ga ni n t e g e rf r o mk e y b o a r d .* / p r i n t f( " % d " ,v a r ) ;/ *u s es t d o u tf o rp r i n t i n gac h a r a c t e r .* /
en.wikibooks.org/wiki/C_Programming/Print_version
57/118
10/24/13
r e t u r n0 ; } / *e n dp r o g r a m .* /
F I L E pointers
The < s t d i o . h > headercontainsadefinitionforatype F I L E (usuallyviaa t y p e d e f )whichiscapableofprocessingalltheinformationneededtoexercisecontroloverastream,includingitsfilepositionindicator,apointertotheassociatedbuffer(ifany),anerror indicatorthatrecordswhetheraread/writeerrorhasoccurred,andanendoffileindicatorthatrecordswhethertheendofthefilehasbeenreached. Itisconsideredbadmannerstoaccessthecontentsof F I L E directlyunlesstheprogrammeriswritinganimplementationof < s t d i o . h > anditscontents.Betteraccesstothecontentsof F I L E isprovidedviathefunctionsin < s t d i o . h > .Itcanbesaidthatthe F I L E typeisanearlyexampleofobjectorientedprogramming.
OpeningandClosingFiles
Toopenandclosefiles,the < s t d i o . h > libraryhasthreefunctions: f o p e n , f r e o p e n ,and f c l o s e .
OpeningFiles
# i n c l u d e< s t d i o . h > F I L E* f o p e n ( c o n s tc h a r* f i l e n a m e ,c o n s tc h a r* m o d e ) ; F I L E* f r e o p e n ( c o n s tc h a r* f i l e n a m e ,c o n s tc h a r* m o d e ,F I L E* s t r e a m ) ;
f o p e n and f r e o p e n opensthefilewhosenameisinthestringpointedtoby f i l e n a m e andassociatesastreamwithit.Bothreturnapointertotheobjectcontrollingthestream,oriftheopenoperationfailsanullpointer.Theerrorandendoffileindicatorsare
r w a r b w b a b r + w + a + r + bo rr b + w + bo rw b + a + bo ra b +
Openingafilewithreadmode('r 'asthefirstcharacterinthe m o d e argument)failsifthefiledoesnotexistorcannotberead. Openingafilewithappendmode('a 'asthefirstcharacterinthe m o d e argument)causesallsubsequentwritestothefiletobeforcedtothethencurrentendoffile,regardlessofinterveningcallstothe f s e e k function.Insomeimplementations,openinga binaryfilewithappendmode('b 'asthesecondorthirdcharacterintheabovelistof m o d e arguments)mayinitiallypositionthefilepositionindicatorforthestreambeyondthelastdatawritten,becauseofnullcharacterpadding. Whenafileisopenedwithupdatemode('+ 'asthesecondorthirdcharacterintheabovelistof m o d e argumentvalues),bothinputandoutputmaybeperformedontheassociatedstream.However,outputmaynotbedirectlyfollowedbyinputwithoutan interveningcalltothe f f l u s h functionortoafilepositioningfunction(f s e e k , f s e t p o s ,or r e w i n d ),andinputmaynotbedirectlyfollowedbyoutputwithoutaninterveningcalltoafilepositioningfunction,unlesstheinputoperationencountersendoffile. Opening(orcreating)atextfilewithupdatemodemayinsteadopen(orcreate)abinarystreaminsomeimplementations. Whenopened,astreamisfullybufferedifandonlyifitcanbedeterminednottorefertoaninteractivedevice.
ClosingFiles
# i n c l u d e< s t d i o . h > i n tf c l o s e ( F I L E* s t r e a m ) ;
Otherfileaccessfunctions
Thef f l u s h function
# i n c l u d e< s t d i o . h > i n tf f l u s h ( F I L E* s t r e a m ) ;
en.wikibooks.org/wiki/C_Programming/Print_version
58/118
10/24/13
If s t r e a m pointstoanoutputstreamoranupdatestreaminwhichthemostrecentoperationwasnotinput,the f f l u s h functioncausesanyunwrittendataforthatstreamtobedeferredtothehostenvironmenttobewrittentothefile.Thebehavioroffflush isundefinedforinputstream. If s t r e a m isanullpointer,the f f l u s h functionperformsthisflushingactiononallstreamsforwhichthebehaviorisdefinedabove. The f f l u s h functionsreturns E O F ifawriteerroroccurs,otherwisezero. Thereasonforhavinga f f l u s h functionisbecausestreamsinCcanhavebufferedinput/outputthatis,functionsthatwritetoafileactuallywritetoabufferinsidethe F I L E structure.Ifthebufferisfilledtocapacity,thewritefunctionswillcall f f l u s h to actually"write"thedatathatisinthebuffertothefile.Because f f l u s h isonlycalledeveryonceinawhile,callstotheoperatingsystemtodoarawwriteareminimized.
Thes e t b u f function
# i n c l u d e< s t d i o . h > v o i ds e t b u f ( F I L E* s t r e a m ,c h a r* b u f ) ;
Thes e t v b u f function
# i n c l u d e< s t d i o . h > i n ts e t v b u f ( F I L E* s t r e a m ,c h a r* b u f ,i n tm o d e ,s i z e _ ts i z e ) ;
The s e t v b u f functionmaybeusedonlyafterthestreampointedtoby s t r e a m hasbeenassociatedwithanopenfileandbeforeanyotheroperationisperformedonthestream.Theargument m o d e determineshowthestreamwillbebuffered,asfollows: _ I O F B F causesinput/outputtobefullybuffered _ I O L B F causesinput/outputtobelinebuffered _ I O N B F causesinput/outputtobeunbuffered.If b u f isnotanullpointer,thearrayitpointstomaybeusedinsteadofabufferassociatedbythe s e t v b u f function.(The buffermusthavealifetimeatleastasgreatastheopenstream,sothestreamshouldbeclosedbeforeabufferthathasautomaticstoragedurationisdeallocateduponblockexit.)Theargument s i z e specifiesthesizeofthearray.Thecontentsofthe arrayatanytimeareindeterminate. The s e t v b u f functionreturnszeroonsuccess,ornonzeroifaninvalidvalueisgivenfor m o d e oriftherequestcannotbehonored.
FunctionsthatModifytheFilePositionIndicator
The s t d i o . h libraryhasfivefunctionsthataffectthefilepositionindicatorbesidesthosethatdoreadingorwriting: f g e t p o s , f s e e k , f s e t p o s , f t e l l ,and r e w i n d . The f s e e k and f t e l l functionsareolderthan f g e t p o s and f s e t p o s .
The f g e t p o s functionstoresthecurrentvalueofthefilepositionindicatorforthestreampointedtoby s t r e a m intheobjectpointedtoby p o s .Thevaluestoredcontainsunspecifiedinformationusablebythe f s e t p o s functionforrepositioningthestreamtoits positionatthetimeofthecalltothe f g e t p o s function. Ifsuccessful,the f g e t p o s functionreturnszeroonfailure,the f g e t p o s functionreturnsnonzeroandstoresanimplementationdefinedpositivevaluein e r r n o . The f s e t p o s functionsetsthefilepositionindicatorforthestreampointedtoby s t r e a m accordingtothevalueoftheobjectpointedtoby p o s ,whichshallbeavalueobtainedfromanearliercalltothe f g e t p o s functiononthesamestream. Asuccessfulcalltothe f s e t p o s functionclearstheendoffileindicatorforthestreamandundoesanyeffectsofthe u n g e t c functiononthesamestream.Afteran f s e t p o s call,thenextoperationonanupdatestreammaybeeitherinputoroutput. Ifsuccessful,the f s e t p o s functionreturnszeroonfailure,the f s e t p o s functionreturnsnonzeroandstoresanimplementationdefinedpositivevaluein e r r n o .
The f s e e k functionsetsthefilepositionindicatorforthestreampointedtoby s t r e a m . Forabinarystream,thenewposition,measuredincharactersfromthebeginningofthefile,isobtainedbyadding o f f s e t tothepositionspecifiedby w h e n c e .Threemacrosin s t d i o . h called S E E K _ S E T , S E E K _ C U R ,and S E E K _ E N D expandtouniquevalues.Iftheposition specifiedby w h e n c e is S E E K _ S E T ,thespecifiedpositionisthebeginningofthefileif w h e n c e is S E E K _ E N D ,thespecifiedpositionistheendofthefileandif w h e n c e is S E E K _ C U R ,thespecifiedpositionisthecurrentfileposition.Abinarystreamneednotmeaningfully support f s e e k callswitha w h e n c e valueof S E E K _ E N D . Foratextstream,either o f f s e t shallbezero,or o f f s e t shallbeavaluereturnedbyanearliercalltothe f t e l l functiononthesamestreamand w h e n c e shallbe S E E K _ S E T . The f s e e k functionreturnsnonzeroonlyforarequestthatcannotbesatisfied.
en.wikibooks.org/wiki/C_Programming/Print_version
59/118
10/24/13
The f t e l l functionobtainsthecurrentvalueofthefilepositionindicatorforthestreampointedtoby s t r e a m .Forabinarystream,thevalueisthenumberofcharactersfromthebeginningofthefileforatextstream,itsfilepositionindicatorcontains unspecifiedinformation,usablebythe f s e e k functionforreturningthefilepositionindicatorforthestreamtoitspositionatthetimeofthe f t e l l callthedifferencebetweentwosuchreturnvaluesisnotnecessarilyameaningfulmeasureofthenumberof characterswrittenorread. Ifsuccessful,the f t e l l functionreturnsthecurrentvalueofthefilepositionindicatorforthestream.Onfailure,the f t e l l functionreturns 1 L andstoresanimplementationdefinedpositivevaluein e r r n o .
Ther e w i n d function
# i n c l u d e< s t d i o . h > v o i dr e w i n d ( F I L E* s t r e a m ) ;
exceptthattheerrorindicatorforthestreamisalsocleared.
ErrorHandlingFunctions
Thec l e a r e r r function
# i n c l u d e< s t d i o . h > v o i dc l e a r e r r ( F I L E* s t r e a m ) ;
The c l e a r e r r functionclearstheendoffileanderrorindicatorsforthestreampointedtoby s t r e a m .
Thef e o f function
# i n c l u d e< s t d i o . h > i n tf e o f ( F I L E* s t r e a m ) ;
Thef e r r o r function
# i n c l u d e< s t d i o . h > i n tf e r r o r ( F I L E* s t r e a m ) ;
Thep e r r o r function
# i n c l u d e< s t d i o . h > v o i dp e r r o r ( c o n s tc h a r* s ) ;
The p e r r o r functionmapstheerrornumberintheintegerexpression e r r n o toanerrormessage.Itwritesasequenceofcharacterstothestandarderrorstreamthus:first,if s isnotanullpointerandthecharacterpointedtoby s isnotthenullcharacter,the stringpointedtoby s followedbyacolon(: )andaspacethenanappropriateerrormessagestringfollowedbyanewlinecharacter.Thecontentsoftheerrormessagearethesameasthosereturnedbythe s t r e r r o r functionwiththeargument e r r n o ,which areimplementationdefined.
OtherOperationsonFiles
The s t d i o . h libraryhasavarietyoffunctionsthatdosomeoperationonfilesbesidesreadingandwriting.
Ther e m o v e function
# i n c l u d e< s t d i o . h > i n tr e m o v e ( c o n s tc h a r* f i l e n a m e ) ;
en.wikibooks.org/wiki/C_Programming/Print_version
60/118
10/24/13
Ther e n a m e function
# i n c l u d e< s t d i o . h > i n tr e n a m e ( c o n s tc h a r* o l d _ f i l e n a m e ,c o n s tc h a r* n e w _ f i l e n a m e ) ;
The r e n a m e functioncausesthefilewhosenameisthestringpointedtoby o l d _ f i l e n a m e tobehenceforthknownbythenamegivenbythestringpointedtoby n e w _ f i l e n a m e .Thefilenamed o l d _ f i l e n a m e isnolongeraccessiblebythatname.Ifafilenamedbythe stringpointedtoby n e w _ f i l e n a m e existspriortothecalltothe r e n a m e function,thebehaviorisimplementationdefined. The r e n a m e functionreturnszeroiftheoperationsucceeds,nonzeroifitfails,inwhichcaseifthefileexistedpreviouslyitisstillknownbyitsoriginalname.
Thet m p f i l e function
# i n c l u d e< s t d i o . h > F I L E* t m p f i l e ( v o i d ) ;
Thet m p n a m function
# i n c l u d e< s t d i o . h > c h a r* t m p n a m ( c h a r* s ) ;
The t m p n a m functiongeneratesastringthatisavalidfilenameandthatisnotthenameofanexistingfile. The t m p n a m functiongeneratesadifferentstringeachtimeitiscalled,upto T M P _ M A X times.(T M P _ M A X isamacrodefinedin s t d i o . h .)Ifitiscalledmorethan T M P _ M A X times,thebehaviorisimplementationdefined. Theimplementationshallbehaveasifnolibraryfunctioncallsthe t m p n a m function. Iftheargumentisanullpointer,the t m p n a m functionleavesitsresultinaninternalstaticobjectandreturnsapointertothatobject.Subsequentcallstothe t m p n a m functionmaymodifythesameobject.Iftheargumentisnotanullpointer,itisassumedto pointtoanarrayofatleast L _ t m p n a m characters(L _ t m p n a m isanothermacroin s t d i o . h )the t m p n a m functionwritesitsresultinthatarrayandreturnstheargumentasitsvalue. Thevalueofthemacro T M P _ M A X mustbeatleast25.
ReadingfromFiles
CharacterInputFunctions
The f g e t c function
# i n c l u d e< s t d i o . h > i n tf g e t c ( F I L E* s t r e a m ) ;
The f g e t c functionobtainsthenextcharacter(ifpresent)asan u n s i g n e dc h a r convertedtoan i n t ,fromtheinputstreampointedtoby s t r e a m ,andadvancestheassociatedfilepositionindicatorforthestream(ifdefined). The f g e t c functionreturnsthenextcharacterfromtheinputstreampointedtoby s t r e a m .Ifthestreamisatendoffile,theendoffileindicatorforthestreamissetand f g e t c returns E O F (E O F isanegativevaluedefinedin < s t d i o . h > ,usually ( 1 ) ).Ifareaderror occurs,theerrorindicatorforthestreamissetand f g e t c returns E O F . The f g e t s function
# i n c l u d e< s t d i o . h > c h a r* f g e t s ( c h a r* s ,i n tn ,F I L E* s t r e a m ) ;
The f g e t s functionreadsatmostonelessthanthenumberofcharactersspecifiedby n fromthestreampointedtoby s t r e a m intothearraypointedtoby s .Noadditionalcharactersarereadafteranewlinecharacter(whichisretained)orafterendoffile.A nullcharacteriswrittenimmediatelyafterthelastcharacterreadintothearray. The f g e t s functionreturns s ifsuccessful.Ifendoffileisencounteredandnocharactershavebeenreadintothearray,thecontentsofthearrayremainunchangedandanullpointerisreturned.Ifareaderroroccursduringtheoperation,thearraycontents areindeterminateandanullpointerisreturned. Warning:Differentoperatingsystemsmayusedifferentcharactersequencestorepresenttheendoflinesequence.Forexample,somefilesystemsusetheterminator \ r \ n intextfiles f g e t s mayreadthoselines,removingthe \ n butkeepingthe \ r asthe lastcharacterof s .Thisexpuriouscharactershouldberemovedinthestring s beforethestringisusedforanything(unlesstheprogrammerdoesn'tcareaboutit).Unixestypicallyuse \ n asitsendoflinesequence,MSDOSandWindowsuses \ r \ n ,and MacOSesused \ r beforeOSX.
en.wikibooks.org/wiki/C_Programming/Print_version
61/118
10/24/13
/ *Ae x a m p l ep r o g r a mt h a tr e a d sf r o ms t d i na n dw r i t e st os t d o u t* / # i n c l u d e< s t d i o . h > # d e f i n eB U F F E R _ S I Z E1 0 0 i n tm a i n ( v o i d ) { c h a rb u f f e r [ B U F F E R _ S I Z E ] ;/ *ar e a db u f f e r* / w h i l e (f g e t s( b u f f e r ,B U F F E R _ S I Z E ,s t d i n )! =N U L L ) { p r i n t f ( " % s " , b u f f e r ) ; } r e t u r n0 ; } / *e n dp r o g r a m .* /
The g e t c function
# i n c l u d e< s t d i o . h > i n tg e t c ( F I L E* s t r e a m ) ;
The g e t c functionisequivalentto f g e t c ,exceptthatitmaybeimplementedasamacro.Ifitisimplementedasamacro,the s t r e a m argumentmaybeevaluatedmorethanonce,sotheargumentshouldneverbeanexpressionwithsideeffects(i.e.havean assignment,increment,ordecrementoperators,orbeafunctioncall). The g e t c functionreturnsthenextcharacterfromtheinputstreampointedtoby s t r e a m .Ifthestreamisatendoffile,theendoffileindicatorforthestreamissetand g e t c returns E O F (E O F isanegativevaluedefinedin < s t d i o . h > ,usually ( 1 ) ).Ifareaderror occurs,theerrorindicatorforthestreamissetand g e t c returns E O F . The g e t c h a r function
# i n c l u d e< s t d i o . h > i n tg e t c h a r ( v o i d ) ;
The g e t c h a r functionisequivalentto g e t c withtheargument s t d i n . The g e t c h a r functionreturnsthenextcharacterfromtheinputstreampointedtoby s t d i n .If s t d i n isatendoffile,theendoffileindicatorfor s t d i n issetand g e t c h a r returns E O F (E O F isanegativevaluedefinedin < s t d i o . h > ,usually ( 1 ) ).Ifareaderroroccurs,the errorindicatorfor s t d i n issetand g e t c h a r returns E O F . The g e t s function
# i n c l u d e< s t d i o . h > c h a r* g e t s ( c h a r* s ) ;
The g e t s functionreadscharactersfromtheinputstreampointedtoby s t d i n intothearraypointedtoby s untilanendoffileisencounteredoranewlinecharacterisread.Anynewlinecharacterisdiscarded,andanullcharacteriswrittenimmediately afterthelastcharacterreadintothearray. The g e t s functionreturns s ifsuccessful.Iftheendoffileisencounteredandnocharactershavebeenreadintothearray,thecontentsofthearrayremainunchangedandanullpointerisreturned.Ifareaderroroccursduringtheoperation,thearray contentsareindeterminateandanullpointerisreturned. Thisfunctionanddescriptionisonlyincludedhereforcompleteness.MostCprogrammersnowadaysshyawayfromusing g e t s ,asthereisnowayforthefunctiontoknowhowbigthebufferisthattheprogrammerwantstoreadinto.Commandment#5of HenrySpencer's TheTenCommandmentsforCProgrammers(AnnotatedEdition)reads,"Thoushaltcheckthearrayboundsofallstrings(indeed,allarrays),forsurelywherethoutypest foosomeonesomedayshalltype supercalifragilisticexpialidocious." Itmentions g e t s intheannotation:"AsdemonstratedbythedeedsoftheGreatWorm,aconsequenceofthiscommandmentisthatrobustproductionsoftwareshouldnevermakeuseof g e t s ( ) ,foritistrulyatooloftheDevil.Thyinterfacesshouldalways informthyservantsoftheboundsofthyarrays,andservantswhospurnsuchadviceorquietlyfailtofollowitshouldbedispatchedforthwithtotheLandOfRm,wheretheycandonofurtherharmtothee." The u n g e t c function
# i n c l u d e< s t d i o . h > i n tu n g e t c ( i n tc ,F I L E* s t r e a m ) ;
The u n g e t c functionpushesthecharacterspecifiedby c (convertedtoan u n s i g n e dc h a r )backontotheinputstreampointedtobystream.Thepushedbackcharacterswillbereturnedbysubsequentreadsonthatstreaminthereverseorderoftheirpushing.A successfulinterveningcall(withthestreampointedtoby s t r e a m )toafilepositioningfunction(f s e e k , f s e t p o s ,or r e w i n d )discardsanypushedbackcharactersforthestream.Theexternalstoragecorrespondingtothestreamisunchanged. Onecharacterofpushbackisguaranteed.Ifthe u n g e t c functioniscalledtoomanytimesonthesamestreamwithoutaninterveningreadorfilepositioningoperationonthatstream,theoperationmayfail. Ifthevalueof c equalsthatofthemacro E O F ,theoperationfailsandtheinputstreamisunchanged.
en.wikibooks.org/wiki/C_Programming/Print_version
Asuccessfulcalltothe u n g e t c functionclearstheendoffileindicatorforthestream.Thevalueofthefilepositionindicatorforthestreamafterreadingordiscardingallpushedbackcharactersshallbethesameasitwasbeforethecharacterswerepushed
62/118
10/24/13
EOFpitfall
Amistakewhenusing f g e t c , g e t c ,or g e t c h a r istoassigntheresulttoavariableoftype c h a r beforecomparingitto E O F .Thefollowingcodefragmentsexhibitthismistake,andthenshowthecorrectapproach(usingtypeint): Mistake
c h a rc ; w h i l e( ( c=g e t c h a r ( ) )! =E O F ) p u t c h a r ( c ) ; i n tc ; w h i l e( ( c=g e t c h a r ( ) )! =E O F ) p u t c h a r ( c ) ;
Correction
Considerasysteminwhichthetype c h a r is8bitswide,representing256differentvalues. g e t c h a r mayreturnanyofthe256possiblecharacters,anditalsomayreturn E O F toindicateendoffile,foratotalof257differentpossiblereturnvalues. When g e t c h a r 'sresultisassignedtoa c h a r ,whichcanrepresentonly256differentvalues,thereisnecessarilysomelossofinformationwhenpacking257itemsinto256slots,theremustbeacollision.The E O F value,whenconvertedto c h a r ,becomes indistinguishablefromwhicheveroneofthe256characterssharesitsnumericalvalue.Ifthatcharacterisfoundinthefile,theaboveexamplemaymistakeitforanendoffileindicatoror,justasbad,iftype c h a r isunsigned,thenbecause E O F isnegative, itcanneverbeequaltoanyunsigned c h a r ,sotheaboveexamplewillnotterminateatendoffile.Itwillloopforever,repeatedlyprintingthecharacterwhichresultsfromconverting E O F to c h a r . However,thisloopingfailuremodedoesnotoccurifthechardefinitionissigned(Cmakesthesignednessofthedefaultchartypeimplementationdependent), [16]assumingthecommonlyused E O F valueof1.However,thefundamentalissueremainsthat ifthe E O F valueisdefinedoutsideoftherangeofthe c h a r type,whenassignedtoa c h a r thatvalueisslicedandwillnolongermatchthefull E O F valuenecessarytoexittheloop.Ontheotherhand,if E O F iswithinrangeof c h a r ,thisguaranteesacollision between E O F andacharvalue.Thus,regardlessofhowsystemtypesaredefined,neveruse c h a r typeswhentestingagainst E O F . Onsystemswhere i n t and c h a r arethesamesize(i.e.,systemsincompatiblewithminimallythePOSIXandC99standards),eventhe"good"examplewillsufferfromtheindistinguishabilityof E O F andsomecharacter'svalue.Theproperwaytohandlethis situationistocheck f e o f and f e r r o r after g e t c h a r returns E O F .If f e o f indicatesthatendoffilehasnotbeenreached,and f e r r o r indicatesthatnoerrorshaveoccurred,thenthe E O F returnedby g e t c h a r canbeassumedtorepresentanactualcharacter.These extrachecksarerarelydone,becausemostprogrammersassumethattheircodewillneverneedtorunononeofthese"big c h a r "systems.Anotherwayistouseacompiletimeassertiontomakesurethat U I N T _ M A X>U C H A R _ M A X ,whichatleastpreventsa programwithsuchanassumptionfromcompilinginsuchasystem.
Directinputfunction:thef r e a d function
# i n c l u d e< s t d i o . h > s i z e _ tf r e a d ( v o i d* p t r ,s i z e _ ts i z e ,s i z e _ tn m e m b ,F I L E* s t r e a m ) ;
The f r e a d functionreads,intothearraypointedtoby p t r ,upto n m e m b elementswhosesizeisspecifiedby s i z e ,fromthestreampointedtoby s t r e a m .Thefilepositionindicatorforthestream(ifdefined)isadvancedbythenumberofcharacterssuccessfully read.Ifanerroroccurs,theresultingvalueofthefilepositionindicatorforthestreamisindeterminate.Ifapartialelementisread,itsvalueisindeterminate. The f r e a d functionreturnsthenumberofelementssuccessfullyread,whichmaybelessthan n m e m b ifareaderrororendoffileisencountered.If s i z e or n m e m b iszero, f r e a d returnszeroandthecontentsofthearrayandthestateofthestreamremain unchanged.
Formattedinputfunctions:thes c a n f familyoffunctions
# i n c l u d e< s t d i o . h > i n tf s c a n f ( F I L E* s t r e a m ,c o n s tc h a r* f o r m a t ,. . . ) ; i n ts c a n f ( c o n s tc h a r* f o r m a t ,. . . ) ; i n ts s c a n f ( c o n s tc h a r* s ,c o n s tc h a r* f o r m a t ,. . . ) ;
The f s c a n f functionreadsinputfromthestreampointedtoby s t r e a m ,undercontrolofthestringpointedtoby f o r m a t thatspecifiestheadmissiblesequencesandhowtheyaretobeconvertedforassignment,usingsubsequentargumentsaspointerstothe objectstoreceiveconvertedinput.Ifthereareinsufficientargumentsfortheformat,thebehaviorisundefined.Iftheformatisexhaustedwhileargumentsremain,theexcessargumentsareevaluated(asalways)butareotherwiseignored. Theformatshallbeamultibytecharactersequence,beginningandendinginitsinitialshiftstate.Theformatiscomposedofzeroormoredirectives:oneormorewhitespacecharactersanordinarymultibytecharacter(neither % orawhitespace character)oraconversionspecification.Eachconversionspecificationisintroducedbythecharacter % .Afterthe % ,thefollowingappearinsequence: Anoptionalassignmentsuppressingcharacter * . Anoptionalnonzerodecimalintegerthatspecifiesthemaximumfieldwidth. Anoptional h , l (ell)or L indicatingthesizeofthereceivingobject.Theconversionspecifiers d , i ,and n shallbeprecededby h ifthecorrespondingargumentisapointerto s h o r ti n t ratherthanapointerto i n t ,orby l ifitisapointerto l o n gi n t . Similarly,theconversionspecifiers o , u ,and x shallbeprecededby h ifthecorrespondingargumentisapointerto u n s i g n e ds h o r ti n t ratherthan u n s i g n e di n t ,orby l ifitisapointerto u n s i g n e dl o n gi n t .Finally,theconversionspecifiers e , f ,and g shallbe precededby l ifthecorrespondingargumentisapointerto d o u b l e ratherthanapointerto f l o a t ,orby L ifitisapointerto l o n gd o u b l e .Ifan h , l ,or L appearswithanyotherformatspecifier,thebehaviorisundefined. Acharacterthatspecifiesthetypeofconversiontobeapplied.Thevalidconversionspecifiersaredescribedbelow.
en.wikibooks.org/wiki/C_Programming/Print_version
63/118
10/24/13
The f s c a n f functionexecuteseachdirectiveoftheformatinturn.Ifadirectivefails,asdetailedbelow,the f s c a n f functionreturns.Failuresaredescribedasinputfailures(duetotheunavailabilityofinputcharacters)ormatchingfailures(duetoinappropriate input). Adirectivecomposedofwhitespacecharacter(s)isexecutedbyreadinginputuptothefirstnonwhitespacecharacter(whichremainsunread)oruntilnomorecharactersremainunread. Adirectivethatisanordinarymultibytecharacterisexecutedbyreadingthenextcharactersofthestream.Ifoneofthecharactersdiffersfromonecomprisingthedirective,thedirectivefails,andthedifferingandsubsequentcharactersremainunread. Adirectivethatisaconversionspecificationdefinesasetofmatchinginputsequences,asdescribedbelowforeachspecifier.Aconversionspecificationisexecutedinthefollowingsteps: Inputwhitespacecharacters(asspecifiedbythe i s s p a c e function)areskipped,unlessthespecificationincludesa [ , c ,or n specifier.(Thewhitespacecharactersarenotcountedagainstthespecifiedfieldwidth.) Aninputitemisreadfromthestream,unlessthespecificationincludesan n specifier.Aninputitemisdefinedasthelongestmatchingsequencesofinputcharacters,unlessthatexceedsaspecifiedfieldwidth,inwhichcaseitistheinitialsubsequenceof thatlengthinthesequence.Thefirstcharacter,ifany,aftertheinputitemremainsunread.Ifthelengthoftheinputitemiszero,theexecutionofthedirectivefailsthisconditionisamatchingfailure,unlessanerrorpreventedinputfromthestream,in whichcaseitisaninputfailure. Exceptinthecaseofa % specifier,theinputitem(or,inthecaseofa % n directive,thecountofinputcharacters)isconvertedtoatypeappropriatetotheconversionspecifier.Iftheinputitemisnotamatchingsequence,theexecutionofthedirectivefails thisconditionisamatchingfailure.Unlessassignmentsuppressionwasindicatedbya * ,theresultoftheconversionisplacedintheobjectpointedtobythefirstargumentfollowingthe f o r m a t argumentthathasnotalreadyreceivedaconversionresult.If thisobjectdoesnothaveanappropriatetype,oriftheresultoftheconversioncannotberepresentedinthespaceprovided,thebehaviorisundefined. Thefollowingconversionspecifiersarevalid:
d
Matchesanoptionallysignedfloatingpointnumber,whoseformatisthesameasexpectedforthesubjectstringofthe s t r t o d function.Thecorrespondingargumentwillbeapointertofloating.
s
Matchesasequenceofnonwhitespacecharacters.(Nospecialprovisionsaremadeformultibytecharacters.)Thecorrespondingargumentshallbeapointertotheinitialcharacterofanarraylargeenoughtoacceptthesequenceandaterminating nullcharacter,whichwillbeaddedautomatically.
[
Matchesanonemptysequenceofcharacters(nospecialprovisionsaremadeformultibytecharacters)fromasetofexpectedcharacters(the scanset ).Thecorrespondingargumentshallbeapointertotheinitialcharacterofanarraylargeenough toacceptthesequenceandaterminatingnullcharacter,whichwillbeaddedautomatically.Theconversionspecifierincludesallsubsequentcharactersinthe f o r m a t string,uptoandincludingthematchingrightbracket(] ).Thecharactersbetween thebrackets(the scanlist )comprisethescanset,unlessthecharacteraftertheleftbracketisacircumflex(^ ),inwhichcasethescansetcontainsallthecharactersthatdonotappearinthescanlistbetweenthecircumflexandtherightbracket.Ifthe conversionspecifierbeginswith [ ] or [ ^ ] ,therightbracketcharacterisinthescanlistandthenextrightbracketcharacteristhematchingrightbracketthatendsthespecificationotherwise,thefirstrightbracketcharacteristheonethatendsthe specification.Ifa characterisinthescanlistandisnotthefirst,northesecondwherethefirstcharacterisa ^ ,northelastcharacter,thebehaviorisimplementationdefined.
c
Matchesasequenceofcharacters(nospecialprovisionsaremadeformultibytecharacters)ofthenumberspecifiedbythefieldwidth(1ifnofieldwidthispresentinthedirective).Thecorrespondingargumentshallbeapointertotheinitial characterofanarraylargeenoughtoacceptthesequence.Nonullcharacterisadded.
p
Matchesasingle % noconversionorassignmentoccurs.Thecompleteconversionspecificationshallbe % % .
en.wikibooks.org/wiki/C_Programming/Print_version
64/118
10/24/13
Ifaconversionspecificationisinvalid,thebehaviorisundefined.
Theconversionspecifiers E , G ,and X arealsovalidandbehavethesameas,respectively, e , g ,and x . Ifendoffileisencounteredduringinput,conversionisterminated.Ifendoffileoccursbeforeanycharactersmatchingthecurrentdirectivehavebeenread(otherthanleadingwhitespace,wherepermitted),executionofthecurrentdirectiveterminates withaninputfailureotherwise,unlessexecutionofthecurrentdirectiveisterminatedwithamatchingfailure,executionofthefollowingdirective(ifany)isterminatedwithaninputfailure. Ifconversionterminatesonaconflictinginputcharacter,theoffendinginputcharacterisleftunreadintheinputstream.Trailingwhitespace(includingnewlinecharacters)isleftunreadunlessmatchedbyadirective.Thesuccessofliteralmatchesand suppressedassignmentsisnotdirectlydeterminableotherthanviathe % n directive. The f s c a n f functionreturnsthevalueofthemacro E O F ifaninputfailureoccursbeforeanyconversion.Otherwise,the f s c a n f functionreturnsthenumberofinputitemsassigned,whichcanbefewerthanprovidedfor,orevenzero,intheeventofanearly matchingfailure. The s c a n f functionisequivalentto f s c a n f withtheargument s t d i n interposedbeforetheargumentsto s c a n f .Itsreturnvalueissimilartothatof f s c a n f . The s s c a n f functionisequivalentto f s c a n f ,exceptthattheargument s specifiesastringfromwhichtheinputistobeobtained,ratherthanfromastream.Reachingtheendofthestringisequivalenttoencounteringtheendoffileforthe f s c a n f function.If copyingtakesplacebetweenobjectsthatoverlap,thebehaviorisundefined.
WritingtoFiles
CharacterOutputFunctions
The f p u t c function
# i n c l u d e< s t d i o . h > i n tf p u t c ( i n tc ,F I L E* s t r e a m ) ;
# i n c l u d e< s t d i o . h > i n tf p u t s ( c o n s tc h a r* s ,F I L E* s t r e a m ) ;
# i n c l u d e< s t d i o . h > i n tp u t c ( i n tc ,F I L E* s t r e a m ) ;
# i n c l u d e< s t d i o . h > i n tp u t c h a r ( i n tc ) ;
# i n c l u d e< s t d i o . h > i n tp u t s ( c o n s tc h a r* s ) ;
Directoutputfunction:thef w r i t e function
en.wikibooks.org/wiki/C_Programming/Print_version
65/118
10/24/13
# i n c l u d e< s t d i o . h > s i z e _ tf w r i t e ( c o n s tv o i d* p t r ,s i z e _ ts i z e ,s i z e _ tn m e m b ,F I L E* s t r e a m ) ;
Formattedoutputfunctions:thep r i n t f familyoffunctions
# i n c l u d e< s t d a r g . h > # i n c l u d e< s t d i o . h > i n tf p r i n t f ( F I L E* s t r e a m ,c o n s tc h a r* f o r m a t ,. . . ) ; i n tp r i n t f ( c o n s tc h a r* f o r m a t ,. . . ) ; i n ts p r i n t f ( c h a r* s ,c o n s tc h a r* f o r m a t ,. . . ) ; i n tv f p r i n t f ( F I L E* s t r e a m ,c o n s tc h a r* f o r m a t ,v a _ l i s ta r g ) ; i n tv p r i n t f ( c o n s tc h a r* f o r m a t ,v a _ l i s ta r g ) ; i n tv s p r i n t f ( c h a r* s ,c o n s tc h a r* f o r m a t ,v a _ l i s ta r g ) ;
Note:SomelengthspecifiersandformatspecifiersarenewinC99.Thesemaynotbeavailableinoldercompilersandversionsofthestdiolibrary,whichadheretotheC89/C90standard.Whereverpossible,thenewoneswillbemarkedwith(C99). The f p r i n t f functionwritesoutputtothestreampointedtoby s t r e a m undercontrolofthestringpointedtoby f o r m a t thatspecifieshowsubsequentargumentsareconvertedforoutput.Ifthereareinsufficientargumentsfortheformat,thebehavioris undefined.Iftheformatisexhaustedwhileargumentsremain,theexcessargumentsareevaluated(asalways)butareotherwiseignored.The f p r i n t f functionreturnswhentheendoftheformatstringisencountered. Theformatshallbeamultibytecharactersequence,beginningandendinginitsinitialshiftstate.Theformatiscomposedofzeroormoredirectives:ordinarymultibytecharacters(not % ),whicharecopiedunchangedtotheoutputstreamandconversion specifications,eachofwhichresultsinfetchingzeroormoresubsequentarguments,convertingthem,ifapplicable,accordingtothecorrespondingconversionspecifier,andthenwritingtheresulttotheoutputstream. Eachconversionspecificationisintroducedbythecharacter % .Afterthe % ,thefollowingappearinsequence: Zeroormoreflags(inanyorder)thatmodifythemeaningoftheconversionspecification. Anoptionalminimumfieldwidth.Iftheconvertedvaluehasfewercharactersthanthefieldwidth,itispaddedwithspaces(bydefault)ontheleft(orright,iftheleftadjustmentflag,describedlater,hasbeengiven)tothefieldwidth.Thefieldwidth takestheformofanasterisk * (describedlater)oradecimalinteger.(Notethat0istakenasaflag,notasthebeginningofafieldwidth.) Anoptionalprecisionthatgivestheminimumnumberofdigitstoappearforthe d , i , o , u , x ,and X conversions,thenumberofdigitstoappearafterthedecimalpointcharacterfor a , A , e , E , f ,and F conversions,themaximumnumberofsignificant digitsforthe g and G conversions,orthemaximumnumberofcharacterstobewrittenfromastringin s conversions.Theprecisiontakestheformofaperiod(. )followedeitherbyanasterisk * (describedlater)orbyanoptionaldecimalintegerif onlytheperiodisspecified,theprecisionistakenaszero.Ifaprecisionappearswithanyotherconversionspecifier,thebehaviorisundefined.Floatingpointnumbersare roundedtofittheprecisioni.e. p r i n t f ( " % 1 . 1 f \ n " ,1 . 1 9 ) ; produces 1 . 2 . Anoptionallengthmodifierthatspecifiesthesizeoftheargument. Aconversionspecifiercharacterthatspecifiesthetypeofconversiontobeapplied. Asnotedabove,afieldwidth,orprecision,orboth,maybeindicatedbyanasterisk.Inthiscase,an i n t argumentsuppliesthefieldwidthorprecision.Theargumentsspecifyingfieldwidth,orprecision,orboth,shallappear(inthatorder)beforethe argument(ifany)tobeconverted.Anegativefieldwidthargumentistakenasa flagfollowedbyapositivefieldwidth.Anegativeprecisionargumentistakenasiftheprecisionwereomitted. Theflagcharactersandtheirmeaningsare:
Theresultoftheconversionisleftjustifiedwithinthefield.(Itisrightjustifiedifthisflagisnotspecified.)
+
Theresultisconvertedtoan"alternativeform".For o conversion,itincreasestheprecision,ifandonlyifnecessary,toforcethefirstdigitoftheresulttobeazero(ifthevalueandprecisionareboth0,asingle0isprinted).For x (or X )conversion,a nonzeroresulthas 0 x (or 0 X )prefixedtoit.For a , A , e , E , f , F , g ,and G conversions,theresultalwayscontainsadecimalpointcharacter,evenifnodigitsfollowit.(Normally,adecimalpointcharacterappearsintheresultoftheseconversionsonlyifa digitfollowsit.)For g and G conversions,trailingzerosarenotremovedfromtheresult.Forotherconversions,thebehaviorisundefined.
0
Thelengthmodifiersandtheirmeaningsare:
h h
en.wikibooks.org/wiki/C_Programming/Print_version
66/118
10/24/13
Specifiesthatafollowing d , i , o , u , x ,or X conversionspecifierappliestoa l o n gi n t or u n s i g n e dl o n gi n t argumentthatafollowing n conversionspecifierappliestoapointertoa l o n gi n t argument(C99)thatafollowing c conversionspecifierappliesto a w i n t _ t argument(C99)thatafollowing s conversionspecifierappliestoapointertoa w c h a r _ t argumentorhasnoeffectonafollowing a , A , e , E , f , F , g ,or G conversionspecifier.
l l (ellell)
The u n s i g n e di n t argumentisconvertedtounsignedoctal(o ),unsigneddecimal(u ),orunsignedhexadecimalnotation(x or X )inthestyle ddddtheletters a b c d e f areusedfor x conversionandtheletters A B C D E F for X conversion.Theprecisionspecifies theminimumnumberofdigitstoappearifthevaluebeingconvertedcanberepresentedinfewerdigits,itisexpandedwithleadingzeros.Thedefaultprecisionis1.Theresultofconvertingazerovaluewithaprecisionofzeroisnocharacters.
f , F
A d o u b l e argumentrepresentinga(finite)floatingpointnumberisconvertedtodecimalnotationinthestyle [ ]ddd. ddd,wherethenumberofdigitsafterthedecimalpointcharacterisequaltotheprecisionspecification.Iftheprecisionismissing,it istakenas6iftheprecisioniszeroandthe # flagisnotspecified,nodecimalpointcharacterappears.Ifadecimalpointcharacterappears,atleastonedigitappearsbeforeit.Thevalueisroundedtotheappropriatenumberofdigits. (C99)A d o u b l e argumentrepresentinganinfinityisconvertedinoneofthestyles [ ]i n f or [ ]i n f i n i t y whichstyleisimplementationdefined.AdoubleargumentrepresentingaNaNisconvertedinoneofthestyles [ ]n a n or [ ]n a n ( ncharsequence) whichstyle,andthemeaningofany ncharsequence,isimplementationdefined.The F conversionspecifierproduces I N F , I N F I N I T Y ,or N A N insteadof i n f , i n f i n i t y ,or n a n ,respectively.(WhenappliedtoinfiniteandNaNvalues,the , + ,and space flagshavetheirusualmeaningthe # and 0 flagshavenoeffect.)
e , E
A d o u b l e argumentrepresentinga(finite)floatingpointnumberisconvertedinthestyle [ ]d. ddde dd,wherethereisonedigit(whichisnonzeroiftheargumentisnonzero)beforethedecimalpointcharacterandthenumberofdigitsafteritisequal totheprecisioniftheprecisionismissing,itistakenas6iftheprecisioniszeroandthe # flagisnotspecified,nodecimalpointcharacterappears.Thevalueisroundedtotheappropriatenumberofdigits.The E conversionspecifierproducesa numberwith E insteadof e introducingtheexponent.Theexponentalwayscontainsatleasttwodigits,andonlyasmanymoredigitsasnecessarytorepresenttheexponent.Ifthevalueiszero,theexponentiszero. (C99)A d o u b l e argumentrepresentinganinfinityorNaNisconvertedinthestyleofan f or F conversionspecifier.
g , G
A d o u b l e argumentrepresentinga(finite)floatingpointnumberisconvertedinstyle f or e (orinstyle F or E inthecaseofa G conversionspecifier),withtheprecisionspecifyingthenumberofsignificantdigits.Iftheprecisioniszero,itistakenas1. Thestyleuseddependsonthevalueconvertedstyle e (or E )isusedonlyiftheexponentresultingfromsuchaconversionislessthan4orgreaterthanorequaltotheprecision.Trailingzerosareremovedfromthefractionalportionoftheresult unlessthe # flagisspecifiedadecimalpointcharacterappearsonlyifitisfollowedbyadigit. (C99)A d o u b l e argumentrepresentinganinfinityorNaNisconvertedinthestyleofan f or F conversionspecifier.
a , A
(C99)Adoubleargumentrepresentinga(finite)floatingpointnumberisconvertedinthestyle [ ]0 x h. hhhhp d,wherethereisonehexadecimaldigit(whichisnonzeroiftheargumentisanormalizedfloatingpointnumberandisotherwise unspecified)beforethedecimalpointcharacter(Binaryimplementationscanchoosethehexadecimaldigittotheleftofthedecimalpointcharactersothatsubsequentdigitsaligntonibble[4bit]boundaries.)andthenumberofhexadecimaldigits afteritisequaltotheprecisioniftheprecisionismissingand F L T _ R A D I X isapowerof2,thentheprecisionissufficientforanexactrepresentationofthevalueiftheprecisionismissingand F L T _ R A D I X isnotapowerof2,thentheprecisionis sufficienttodistinguish(Theprecision pissufficienttodistinguishvaluesofthesourcetypeif16p1> bnwhere bis F L T _ R A D I X and nisthenumberofbasebdigitsinthesignificandofthesourcetype.Asmaller pmightsufficedependingonthe implementation'sschemefordeterminingthedigittotheleftofthedecimalpointcharacter.)valuesoftype d o u b l e ,exceptthattrailingzerosmaybeomittediftheprecisioniszeroandthe # flagisnotspecified,nodecimalpointcharacterappears.
en.wikibooks.org/wiki/C_Programming/Print_version
67/118
10/24/13
Theletters a b c d e f areusedfor a conversionandtheletters A B C D E F for A conversion.The A conversionspecifierproducesanumberwith X and P insteadof x and p .Theexponentalwayscontainsatleastonedigit,andonlyasmanymoredigitsas necessarytorepresentthedecimalexponentof2.Ifthevalueiszero,theexponentiszero. A d o u b l e argumentrepresentinganinfinityorNaNisconvertedinthestyleofan f or F conversionspecifier.
c
Ifno l lengthmodifierispresent,theargumentshallbeapointertotheinitialelementofanarrayofcharactertype.(Nospecialprovisionsaremadeformultibytecharacters.)Charactersfromthearrayarewrittenupto(butnotincluding)the terminatingnullcharacter.Iftheprecisionisspecified,nomorethanthatmanycharactersarewritten.Iftheprecisionisnotspecifiedorisgreaterthanthesizeofthearray,thearrayshallcontainanullcharacter. (C99)Ifan l lengthmodifierispresent,theargumentshallbeapointertotheinitialelementofanarrayof w c h a r _ t type.Widecharactersfromthearrayareconvertedtomultibytecharacters(eachasifbyacalltothe w c r t o m b function,withthe conversionstatedescribedbyan m b s t a t e _ t objectinitializedtozerobeforethefirstwidecharacterisconverted)uptoandincludingaterminatingnullwidecharacter.Theresultingmultibytecharactersarewrittenupto(butnotincluding)the terminatingnullcharacter(byte).Ifnoprecisionisspecified,thearrayshallcontainanullwidecharacter.Ifaprecisionisspecified,nomorethanthatmanycharacters(bytes)arewritten(includingshiftsequences,ifany),andthearrayshallcontain anullwidecharacterif,toequalthemultibytecharactersequencelengthgivenbytheprecision,thefunctionwouldneedtoaccessawidecharacteronepasttheendofthearray.Innocaseisapartialmultibytecharacterwritten.(Redundantshift sequencesmayresultifmultibytecharactershaveastatedependentencoding.)
p
Theargumentshallbeapointerto v o i d .Thevalueofthepointerisconvertedtoasequenceofprintablecharacters,inanimplementationdefinedmanner.
n
A % characteriswritten.Noargumentisconverted.Thecompleteconversionspecificationshallbe % % . Ifaconversionspecificationisinvalid,thebehaviorisundefined.Ifanyargumentisnotthecorrecttypeforthecorrespondingcoversionspecification,thebehaviorisundefined. Innocasedoesanonexistentorsmallfieldwidthcausetruncationofafieldiftheresultofaconversioniswiderthanthefieldwidth,thefieldisexpandedtocontaintheconversionresult. For a and A conversions,if F L T _ R A D I X isapowerof2,thevalueiscorrectlyroundedtoahexadecimalfloatingnumberwiththegivenprecision. Itisrecommendedpracticethatif F L T _ R A D I X isnotapowerof2,theresultshouldbeoneofthetwoadjacentnumbersinhexadecimalfloatingstylewiththegivenprecision,withtheextrastipulationthattheerrorshouldhaveacorrectsignforthecurrent roundingdirection. Itisrecommendedpracticethatfor e , E , f , F , g ,and G conversions,ifthenumberofsignificantdecimaldigitsisatmost D E C I M A L _ D I G ,thentheresultshouldbecorrectlyrounded.(Forbinarytodecimalconversion,theresultformat'svaluesarethenumbers representablewiththegivenformatspecifier.Thenumberofsignificantdigitsisdeterminedbytheformatspecifier,andinthecaseoffixedpointconversionbythesourcevalueaswell.)Ifthenumberofsignificantdecimaldigitsismorethan D E C I M A L _ D I G butthesourcevalueisexactlyrepresentablewith D E C I M A L _ D I G digits,thentheresultshouldbeanexactrepresentationwithtrailingzeros.Otherwise,thesourcevalueisboundedbytwoadjacentdecimalstrings L<U,bothhaving D E C I M A L _ D I G significantdigits thevalueoftheresultantdecimalstring Dshouldsatisfy LDU,withtheextrastipulationthattheerrorshouldhaveacorrectsignforthecurrentroundingdirection. The f p r i n t f functionreturnsthenumberofcharacterstransmitted,oranegativevalueifanoutputorencodingerroroccurred. The p r i n t f functionisequivalentto f p r i n t f withtheargument s t d o u t interposedbeforetheargumentsto p r i n t f .Itreturnsthenumberofcharacterstransmitted,oranegativevalueifanoutputerroroccurred. The s p r i n t f functionisequivalentto f p r i n t f ,exceptthattheargument s specifiesanarrayintowhichthegeneratedinputistobewritten,ratherthantoastream.Anullcharacteriswrittenattheendofthecharacterswrittenitisnotcountedaspartofthe returnedsum.Ifcopyingtakesplacebetweenobjectsthatoverlap,thebehaviorisundefined.Thefunctionreturnsthenumberofcharacterswritteninthearray,notcountingtheterminatingnullcharacter. The v f p r i n t f functionisequivalentto f p r i n t f ,withthevariableargumentlistreplacedby a r g ,whichshallhavebeeninitializedbythe v a _ s t a r t macro(andpossiblysubsequent v a _ a r g calls).The v f p r i n t f functiondoesnotinvokethe v a _ e n d macro.Thefunction returnsthenumberofcharacterstransmitted,oranegativevalueifanoutputerroroccurred. The v p r i n t f functionisequivalentto p r i n t f ,withthevariableargumentlistreplacedby a r g ,whichshallhavebeeninitializedbythe v a _ s t a r t macro(andpossiblysubsequent v a _ a r g calls).The v p r i n t f functiondoesnotinvokethe v a _ e n d macro.Thefunction returnsthenumberofcharacterstransmitted,oranegativevalueifanoutputerroroccurred. The v s p r i n t f functionisequivalentto s p r i n t f ,withthevariableargumentlistreplacedby a r g ,whichshallhavebeeninitializedbythe v a _ s t a r t macro(andpossiblysubsequent v a _ a r g calls).The v s p r i n t f functiondoesnotinvokethe v a _ e n d macro.Ifcopying takesplacebetweenobjectsthatoverlap,thebehaviorisundefined.Thefunctionreturnsthenumberofcharacterswrittenintothearray,notcountingtheterminatingnullcharacter.
References
1. Severalprogrammersrecommend"usespacesforindentation.Donotusetabsinyourcode.Youshouldsetyoureditortoemitspaceswhenyouhitthetabkey."[1](http://googlestyleguide.googlecode.com/svn/trunk/cppguide.xml)[2] (http://www.jwz.org/doc/tabsvsspaces.html)Otherprogrammersdisagree.[3](http://diagrammesmodernes.blogspot.com/2006/04/tabversusspaces.html)[4](http://www.derkarl.org/why_to_tabs.html)Regardlessofwhetheryoupreferspacesor tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5](http://www.oualline.com/vimcook.html#drawing)
en.wikibooks.org/wiki/C_Programming/Print_version
68/118
10/24/13
Beginningexercises
Variables
Naming
1. Canavariablenamestartwithanumber?can't 2. Canavariablenamestartwithatypographicalsymbolcan't(e.g.#,*,_)? 3. GiveanexampleofaCvariablenamethatwould not work.Whydoesn'titwork? Solution 1. No,thenameofavariablemustbeginwithaletter(lowercaseoruppercase),oranunderscore. 2. Onlytheunderscorecanbeused. 3. forexample, #nm*rtisnotallowedbecause#and*arenotthevalidcharactersforthenameofavariable.
# i n c l u d e < s t d i o . h > m a i n ( ) { i n ta , b , c , m a x ; c l r s c r ( ) ; p r i n t f ( " \ n e n t e rt h r e en u m b e r s" ) ; s c a n f ( " % d% d% d " , & a , & b , & c ) ; m a x = a ; i f ( m a x < b ) m a x = b ; i f ( m a x < c ) m a x = c ; p r i n t f ( " \ n l a r g e s t = % d\ n " , m a x ) ; g e t c h ( ) ; }
DataTypes
1. ListatleastthreedatatypesinC 1. Onyourcomputer,howmuchmemorydoeseachrequire? 2. Whichonescanbeusedinplaceofanother?Why? 1. Arethereanylimitationsontheseuses? 2. Ifso,whatarethey? 3. Isitnecessarytodoanythingspecialtousethealternative? 2. Canthenameweuseforadatatype(e.g.'int','float')beusedasavariable? Solution 3datatypes: longint, shortint, float. Onmycomputer: longint:4byte shortint:2bytes float:4bytes wecannotuse'int'or'float'asavariable'sname.
Assignment
1. Howwouldyouassignthevalue3.14toavariablecalledpi?
en.wikibooks.org/wiki/C_Programming/Print_version
69/118
10/24/13
2. Isitpossibletoassignan int toa double? 1. Isthereversepossible?
Solution Thestandardwayofassigning3.14topiis:
d o u b l ep i ; p i = 3 . 1 4 ;
Sincepiisaconstant,goodprogrammingconventiondictatestomakeitunchangeableduringruntime.Extracreditifyouuseoneofthefollowingtwolines:
c o n s tf l o a tp i=3 . 1 4 ; # d e f i n ep i3 . 1 4
Yes,forexample:
i n ta = 6 7 ; d o u b l eb ; b = a ;
Yes,butacastisnecessaryandthedoubleistruncated:
d o u b l ea = 8 9 ; i n tb ; b = ( i n t )a ;
Referencing
1. Acommonmistakefornewstudentsisreversingtheassignmentstatement.Supposeyouwanttoassignthevaluestoredinthevariable"pi"toanothervariable,say"pi2": 1. Whatisthecorrectstatement? 2. Whatisthereverse?IsthisavalidCstatement(evenifitgivesincorrectresults)? 3. Whatifyouwantedtoassignaconstantvalue(like3.1415)to"pi2": a.Whatwouldthecorrectstatementlooklike? b.WouldthereversebeavalidorinvalidCstatement? Solution 1. p i 2=p i ; 2. Thereverse, p i=p i 2 ; isavalidCstatementif p i isnotaconstant. 3. a. p i 2=3 . 1 4 1 5 ; b.Thereverse: 3 . 1 4 1 5=p i 2 ; isnotvalidsinceitisimpossibletoassignavaluetoaliteral.
SimpleI/O
Input
1. scanf()isaverypowerfulfunction.Describesomefeaturesthatmakeitsoversatile. 2. Writethescanf()functioncallthatwillreadintothevariable"var":
en.wikibooks.org/wiki/C_Programming/Print_version
70/118
10/24/13
1. afloat 2. anint 3. adouble
Solution
Stringmanipulation
1.Writeaprogramthatpromptstheuserforastring,andprintsitsreverse. Solution Onepossiblesolutioncouldbe:
# i n c l u d e< s t d i o . h > # i n c l u d e< s t r i n g . h > i n tm a i n ( v o i d ) { c h a rs [ 8 1 ] ;/ /As t r i n go fu p t o8 0c h a r s+' \ 0 ' i n ti ; p u t s ( " P l e a s ew r i t eas t r i n g :" ) ; f g e t s ( s ,8 1 ,s t d i n ) ; p u t s ( " Y o u rs e n t e n c ei nr e v e r s e :" ) ; f o r( i =s t r l e n ( s ) 1 ;i> =0 ;i ) { i f( s [ i ]= =' \ n ' ) c o n t i n u e ;/ /d o n ' tw r i t en e w l i n e e l s e p u t c h a r ( s [ i ] ) ; } p u t c h a r ( ' \ n ' ) ; r e t u r n0 ; }
# i n c l u d e< s t d i o . h > i n tm a i n ( v o i d ) { c h a rs [ 8 1 ] ,w o r d [ 8 1 ] ; i n tn =0 ,i d x =0 ; p u t s ( " P l e a s ew r i t eas e n t e n c e : " ) ; f g e t s ( s ,8 1 ,s t d i n ) ; / *% sm a t c h e sas e q u e n c eo fn o n w h i t e s p a c ec h a r a c t e r ,w h i c hi sa * f a i rd e f i n i t i o no f" w o r d "i nt h i sc o n t e x t . *% nm a t c h e sn o t h i n g ,b u ts t o r e st h en u m b e ro fc h a r a c t e r st h a th a v e * b e e np r o c e s s e d .i . e .i fsi s" H e l l o ,W o r l d ! " ,t h e nw o r da n dn * w i l lb e" H e l l o , "a n d6r e s p e c t i v e l yi nt h ef i r s ti t e r a t i o n .I n * t h es e c o n di t e r a t i o nt h e yw i l lb e" W o r l d ! "a n d7( 6c h a r s+ * t h es p a c ei nf r o n to ft h ew o r d ) . * / w h i l e(s s c a n f ( & s [ i d x ] ," % s % n " ,w o r d ,& n )>0) { i d x+ =n ; p u t s ( w o r d ) ; }
en.wikibooks.org/wiki/C_Programming/Print_version
71/118
10/24/13
r e t u r n0 ; }
Loops
1.Writeafunctionthatoutputsarightisoscelestriangleofheightandwidth n,so n=3wouldlooklike
* * * * * *
Solution Onepossiblesolution:
Solution Onepossiblesolution:
v o i ds i d e w a y s ( i n tn ) { i n tx , y ; f o r( y =0 ;y<n ;y + + ) { f o r( x =0 ;x< =y ;x + + ) p u t c h a r ( ' * ' ) ; p u t c h a r ( ' \ n ' ) ; } f o r( y =n 1 ;y>0 ;y ) { f o r( x =0 ;x<y ;x + + ) p u t c h a r ( ' * ' ) ; p u t c h a r ( ' \ n ' ) ; } }
orlikethis(allmath)
v o i ds i d e w a y s ( i n tn ) { i n ti = 0 , j = 0 ; f o r ( i = 1 ; i < 2 * n ; i + + ) { f o r ( j = 1 ; j < = ( n ( a b s ( n i ) ) ) ; j + + ) {
en.wikibooks.org/wiki/C_Programming/Print_version
72/118
10/24/13
p r i n t f ( " * " ) ; } p r i n t f ( " \ n " ) ; } }
Solution Onepossiblesolution:
ProgramFlow
1.Buildaprogramwherecontrolpassesfrommaintofourdifferentfunctionswith4calls. 2.Nowmakeawhileloopinmainwiththefunctioncallsinsideit.Askforinputatthebeginningoftheloop.EndthewhileloopiftheuserhitsQ 3.Nextaddconditionalstocallthefunctionswhentheuserentersnumbers,so1goestofunction1,2goestofunction2,etc. 4.Havefunction1callfunctiona,whichcallsfunctionb,whichcallsfunctionc 5.Drawoutadiagramofprogramflow,witharrowstoindicatewherecontrolgoes
Functions
1.Writeafunctiontocheckifanintegerisnegativethedeclarationshouldlooklikeboolis_positive(inti) 2.Writeafunctiontoraiseafloatingpointnumbertoanintegerpower,soforexampletowhenyouuseit floata=raise_to_power(2,3)//agets8 floatb=raise_to_power(9,2)//bgets81 floatraise_to_power(floatf,intpower)//makethisyourdeclaration
Math
1.Writeafunctiontocalculateifanumberisprime.Return1ifitisprimeand0ifitisnotaprime. Solution Onepossiblesolutionusinganaveprimalitytest:
/ /t oc o m p i l e :g c cW a l lp r i m e . cl mop r i m e
en.wikibooks.org/wiki/C_Programming/Print_version
73/118
10/24/13
# i n c l u d e< m a t h . h > / /f o rt h es q u a r er o o tf u n c t i o ns q r t ( ) # i n c l u d e< s t d i o . h > i n ti s _ p r i m e ( i n tn ) ; i n tm a i n ( ) { p r i n t f ( " W r i t ea ni n t e g e r :" ) ; i n tv a r ; s c a n f ( " % d " ,& v a r ) ; i f( i s _ p r i m e ( v a r ) = = 1 ){ p r i n t f ( " Ap r i m e \ n " ) ; }e l s e{ p r i n t f ( " N o tap r i m e \ n " ) ; } r e t u r n1 ; } i n ti s _ p r i m e ( i n tn ) { i n tx ; i n ts q =s q r t ( n ) + 1 ; / /C h e c k i n gt h et r i v i a lc a s e sf i r s t i f(n<2) r e t u r n0 ; i f(n= =2| |n= =3) r e t u r n1 ; / /C h e c k i n gi fni sd i v i s i b l eb y2o ro d dn u m b e r sb e t w e e n3a n dt h e / /s q u a r er o o to fn . i f(n%2= =0) r e t u r n0 ; f o r( x =3 ;x< =s q ;x+ =2 ) { i f(n%x= =0) r e t u r n0 ; } r e t u r n1 ; }
Recursion
Mergesort 1.WriteaCprogramtogeneratearandomintegerarraywithagivenlengthn,andsortitrecursivelyusingtheMergesortalgorithm. Themergesortalgorithmisarecursivealgorithm. sortingaoneelementarrayiseasy. sortingtwooneelementarrays,requiresthemergeoperation.Themergeoperationlooksattwosortedarraysaslists,andcomparestheheadofthelist,andwhicheverheadissmaller,thiselementisputonthesortedlistandtheheadofthatlistis tickedoff,sothenextelementbecomestheheadofthatlist.Thisisdoneuntiloneofthelistsisexhausted,andtheotherlististhencopiedontotheendofthesortedlist. therecursionoccurs,becausemergingtwooneelementarraysproducesonetwoelementsortedarray,whichcanbemergedwithanothertwoelementsortedarrayproducedthesameway.Thisproducesasorted4elementarray,andthesameapplies foranother4elementsortedarray. sothebasicmergesort,istocheckthesizeoflisttobesorted,andifitisgreaterthanone,dividethearrayintotwo,andcallmergesortagainonthetwohalves.Afterwards,mergethetwohalvesinatemporaryspaceofequalsize,andthencopy backthefinalsortedarrayontotheoriginalarray. Solution Onepossiblesolution,afterreadingonlinedescriptionsofrecursivemergesort,e.g.Dasgupta:
/ /t oc o m p i l e :g c cW a l lr m e r g e s o r t . cl mor m e r g e s o r t
en.wikibooks.org/wiki/C_Programming/Print_version
74/118
10/24/13
/ * = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = N a m e :r m e r g e s o r t . c A u t h o r :A n o n V e r s i o n :0 . 1 C o p y r i g h t :( C ) 2 0 1 3u n d e rC C B y S A3 . 0L i c e n s e D e s c r i p t i o n:R e c u r s i v eM e r g eS o r t ,A n s i s t y l e = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / # i n c l u d e< s t d i o . h > # i n c l u d e< s t d l i b . h > # i n c l u d e< s t r i n g . h > / / c o n s ti n tM A X=2 0 0 ; c o n s ti n tM A X=2 0 0 0 0 0 0 0 ; i n t* b ; i n tp r i n t O f f=0 ; / /t h i sd e b u g g i n gp r i n to u to ft h ea r r a yh e l p st os h o w / /w h a ti sg o i n go n . v o i dp r i n t A r r a y ( c h a r *l a b e l ,i n t *a ,i n ts z ){ i n th=s z /2 ; i n ti ; i f( p r i n t O f f )r e t u r n ; p r i n t f ( " \ n % s : \ n " ,l a b e l ) ; f o r( i=0 ;i<h ;+ + i){ p r i n t f ( " % d % c " ,a [ i ] , / /a d di nan e w l i n ee v e r y2 0n u m b e r s ((i! =0& &i%2 0= =0) ?' \ n ' :'')) ; } p r i n t f ( "|" ) ; f o r( ; i<s z ;+ + i ){ p r i n t f ( " % d % c " ,a [ i ] , ((i! =0& &i%2 0= =0) ?' \ n ' :'')) ; } p u t c h a r ( ' \ n ' ) ; } v o i dm e r g e s o r t ( i n t *a ,i n tm){ p r i n t A r r a y ( " B E F O R E " ,a ,m ) ; i f( m>2 ){ / /i fg r e a t e rt h a n2e l e m e n t s ,t h e nr e c u r s i v e m e r g e s o r t ( a ,m/2 ) ; m e r g e s o r t ( a+m/2 ,m-m/2 ) ; }e l s ei f( m= =2& &a [ 0 ]>a [ 1 ] ){ / /i fe x a c t l y2e l e m e n t sa n dn e e ds w a p p i n g ,s w a p i n tt=a [ 1 ] ; a [ 1 ]=a [ 0 ] ; a [ 0 ]=t ; g o t oe n d ; } / /1o rg r e a t e rt h a n2e l e m e n t sw h i c hh a v eb e e nr e c u r s i v e l ys o r t e d / /d i v i d et h ea r r a yi n t oal e f ta n dr i g h ta r r a y / /m e r g ei n t ot h ea r r a ybw i t hi n d e xl . i n tn=m / 2 ; i n to=m-n ; i n ti=0 ,j=n ; i n tl=0 ; / /ii sl e f t ,ji sr i g h t; / /ls h o u l de q u a lmt h es i z eo ft h ea r r a y w h i l e( i<n ){ i f(j> =m ){ / /t h er i g h ta r r a yh a sf i n i s h e d ,s oc o p yt h er e m a i n i n gl e f ta r r a y f o r ( ;i<n ;+ + i ){ b [ l + + ]=a [ i ] ; } / /t h em e r g eo p e r a t i o ni st oc o p yt h es m a l l e rc u r r e n te l e m e n ta n d / /i n c r e m e n tt h ei n d e xo ft h ep a r e n ts u b a r r a y . }e l s ei f ( a [ i ]<a [ j ]){
en.wikibooks.org/wiki/C_Programming/Print_version
75/118
10/24/13
b [ l + + ]=a [ i + + ] ; }e l s e{ b [ l + + ]=a [ j + + ] ; } } w h i l e(j<m ){ / /c o p yt h er e m a i n i n gr i g h ta r r a y,i fa n y b [ l + + ]=a [ j + + ] ; } m e m c p y ( a ,b ,s i z e o f ( i n t )*l) ; e n d : p r i n t A r r a y ( " A F T E R " ,a ,m ) ; r e t u r n ; } v o i dr a n d _ i n i t ( i n t *a ,i n tn ){ i n ti ; f o r( i=0 ;i<n ;+ + i){ a [ i ]=r a n d ( )%M A X ; } } i n tm a i n ( v o i d ){ p u t s ( " ! ! ! H e l l oW o r l d ! ! ! " ) ;/ *p r i n t s! ! ! H e l l oW o r l d ! ! !* / / / / / / / i n tN=2 0 ; i n tN=1 0 0 0 ; i n tN=1 0 0 0 0 0 0 ; i n tN=1 0 0 0 0 0 0 0 0 ; / /s t i l lc a n ' tm a k eas t a c ko v e r f l o wo nu b u n t u , 4 G B ,p h e n o m p r i n t O f f=1 ; i n t* a ; b=c a l l o c (N ,s i z e o f ( i n t ) ) ; a=c a l l o c (N ,s i z e o f ( i n t ) ) ; r a n d _ i n i t ( a ,N ) ; m e r g e s o r t ( a ,N ) ; p r i n t O f f=0 ; p r i n t A r r a y ( " L A S T " ,a ,N ) ; f r e e ( a ) ; f r e e ( b ) ; r e t u r nE X I T _ S U C C E S S ; } / *H a v i n gf a i l e dt ot r a n s l a t em yc o n c e p to fn o n r e c u r s i v em e r g es o r t , *It a c k l e dt h ee a s i e rc a s eo fr e c u r s i v em e r g es o r t . *T h en e x tt a s ki st ot r a n s l a t et h er e c u r s i v ev e r s i o nt oan o n r e c u r s i v e *v e r s i o n .T h i sc o u l db ed o n eb yr e p l a c i n gc a l l st om e r g e s o r t ,w i t h *p u s h e so n t oas t a c ko f *t u p l e so f(< a r r a ys t a r ta d d r e s s > ,< n u m b e ro fe l e m e n t st op r o c e s s >) * / / *T h ec e n t r a li d e ao fm e r g i n g ,i st h a tt w os o r t e dl i s t sc a nb e *m e r g e di n t oo n es o r t e dl i s t ,b yc o m p a r i n gt h et o po fe a c hl i s ta n d *m o v i n gt h el o w e s tv a l u e de l e m e n to n t ot h ee n do ft h en e wl i s t . * T h eo t h e rl i s tw h i c hh a st h eh i g h e rv a l u e de l e m e n tk e e p si t st o p * e l e m e n tu n c h a n g e d .W h e nal i s ti se x h a u s t e d ,c o p yt h er e m a i n i n go t h e rl i s t * o n t ot h ee n do ft h en e wl i s t . * / / *T h er e c u r s i v ep a r t ,i st od e f e ra n yw o r ki ns o r t i n ga nu n s o r t e dl i s t , *b yd i v i d i n gi ti n t ot w ol i s t su n t i lt h e r ei so n l y1o rt w oe l e m e n t s , *a n di ft h e r ea r et w oe l e m e n t s ,s o r tt h e md i r e c t l yb ys w a p p i n gi f *t h ef i r s te l e m e n ti sl a r g e rt h a nt h es e c o n de l e m e n t . * *A f t e rr e t u r n i n gf r o mar e c u r s i v ec a l l ,m e r g et h el i s t s ,w h i c hw i l l *b e g i nw i t ho n eo rt w oe l e m e n ts o r t e dl i s t s .T h er e s u l ti sas o r t e dl i s t *w h i c hw i l lb er e t u r n e dt ot h ep a r e n to ft h er e c u r s i v ec a l l ,a n dc a n *b eu s e df o rm e r g i n g . * / / *T h ef o l l o w i n gi sa ni m a g i n a r yd i s c u s s i o na b o u tw h a tap r o g r a m m e r *m i g h tb et h i n k i n ga b o u tw h e np r o g r a m m i n g : * *V i s u a l i s i n gr e c u r s i o ni nt e r m so faZ 8 0a s s e m b l yl a n g u a g e ,w h i c h
en.wikibooks.org/wiki/C_Programming/Print_version
76/118
10/24/13
Binaryheaps 2. Binaryheaps: Abinarymaxheaporminheap,isanorderedstructurewheresomenodesareguaranteedgreaterthanothernodes,e.g.theparentvstwochildren.Abinaryheapcanbestoredinanarray,where, givenaposition i (theparent), i*2istheleftchild,and i*2+1istherightchild. (Carraysbeginatposition0,but0*2=0,and0*2+1=1,whichisincorrect,sostarttheheapatposition1,oradd1forparenttochildcalculations,andsubtract1forchildtoparentcalculations). trytomodelthisusingwithapencilandpaper,using10randomunsortednumbers,andinsertingeachofthemintoa"heapsort"arrayof10elements. Toinsertintoaheap, endaddand swapparentifhigher,untilparenthigher. Todeletethetopofaheap,move endtotop,and deferhigherchildor siftdown,untilnochildishigher. tryitonapenandpaperthenumbers10,4,6,3,5,11. penandpapersolution 10,4,6,3,5,11>10 4,6,3,5,11>10,4:4isendadded,noswapparentbecause4<10. 6,3,5,11>10,4,6:6isendadded,noswapparentbecause6<10. 3,5,11>10,4,6,3:3isendadded,3isposition4,divideby2=2,4atposition2,noswapparentbecause4>3. 5,11>10,4,6,3,5:5isendadded,5isposition5,dividedby2=2,4atposition2,swapparentas4<55atposition2,noswapparentbecause5<10atposition1. 10,5,6,3,4 11>10,5,6,3,4,11:11isendadded,11isposition6,divideby2=3,swap6with11,11isposition3,swap11with10,stopasnoparent. 11,5,10,3,4,6 11haschildren5,105haschildren3and410haschild6.Parentalways>child.
theanswerwas11,5,10,3,4,6. EXERCISE:Nowtryremovingeachtopelementof11,5,10,3,4,6,usingendtotopandsiftdown(orswaphigherchild)togetthenumbers indescendingorder. penandpapersolution 11leaves*,5,10,3,4,6>6,5,10,3,4> siftdown>choosegreaterchild5(2*n+0)or10(2*n+1)>is6>10?no>swap10and6> 10,5,*6,3,4>4isgreatestchildasno+1child.is6>4?yes,stop. 10leaves*,5,6,3,4>*4,5,6,3>isleft(0)orright(+1)childgreater>+1isgreateris4>+1child?no,swap 6,5,*4,3>*4hasnochildrensostop. 6leaves*,5,4,3>*3,5,4>+0childisgreater>is3>5?no,soswap>5,*3,4,*3hasnochildsostop. is
en.wikibooks.org/wiki/C_Programming/Print_version
77/118
10/24/13
apriorityqueueallowselementstobeinsertedwithapriority,andextractedaccordingtopriority.(Thiscanhappenusefully,iftheelementhasapairedstructure,onepartisthekey,andtheotherpartthedata.Otherwise,itisjustamechanism forsorting). EXERCISE:Usingtheabovetechniqueofinsertback/challengeparent,anddeletefront/lasttofront/deferhigherchild,implementeitherheapsortorapriorityqueue. Dijsktra'salgorithm Dijsktra'salgorithmisasearchingalgorithmusingapriorityqueue.Itbeginswithinsertingthestartnodewithapriorityvalueof0.AllothernodesareinsertedwithpriorityvaluesoflargeN.Eachnodehasanadjacencylistofothernodes,acurrent distancetostartnode,andpreviouspointertopreviousnodeusedtocalculatecurrentnode.Alternativetoanadjacencylist,isanadjacencymatrix,whichneedsnxnbooleanadjacencies. Theagorithmbasicallyiteratesoverthepriorityqueue,removingthefrontnode,examiningtheadjacentnodes,andupdatingwithadistanceequaltothesumofthefrontnodesdistanceforeachadjacentnode,andthedistancegivenbytheadjacency informationforanadjacentnode. Aftereachnode'supdate,theextraoperation "updatepriority"isusedonthatnode: whilethenode'sdistanceislessthanit'sparentsnode(forthispriorityqueue,parentshavelesserdistancesthanthechildren),thenodeisswappedwiththeparent. Afterthis, whilethenodeisgreaterdistancethanoneormoreofitschildren,itisswappedwiththeleastdistantchild,sotheleastdistantchildbecomesparentofitsgreaterdistantsibling,andparenttothegreaterdistantcurrentnode. Withupdatingthepriority,theadjacentnodetothecurrentnodehasabackpointerchangedtothecurrentnode. Thealgorithmendswhenthetargetnodebecomesthecurrentnoderemoved,andthepathtothestartnodecanberecordedinanarraybyfollowingbackpointers,andthendoingsomethinglikeaquicksortpartitiontoreversetheorderofthearray,to givetheshortestpathtotargetnodefromthestartnode. Quicksort 3.WriteaCprogramtorecursivelysortusingtheQuicksortpartitionexchangealgorithm. youcanusethe"driver",ortherandomnumbertestdatafromQ1.onmergesort.Thisis"reuse",whichisencouragedingeneral. anadvantageofreuseislesswritingtime,debuggingtime,testingtime. theconceptofpartitionexchangeisthatapartitionelementis(randomly)selected,andeverythingthatneedssortedisputinto3equivalance classes:thoseelementslessthanthepartitionvalue,thepartitionelement,andeverythingabove(andequalto)thepartitionelement. thiscanbedonewithoutallocatingmorespacethanonetemporaryelementspaceforswappingtwoelements.e.gatemporaryintegerforintegerdata. However,wherethepartitionelementshouldbeusingtheoriginalarrayspaceisnotknown. Thisisusuallyimplementedwithputtingthepartitionontheendofthearraytobesorted,andthenputtingtwopointers,oneatthestartofthearray, andoneattheelementnexttothepartitionelement,andrepeatedlyscanningtheleftpointerright,andtherightpointerleft. theleftscanstopswhenanelementequaltoorgreaterthanthepartitionisfound,andtherightscanstopsforasmallerelementthanthepartitionvalue, andtheseareswapped,whichusesthetemporaryextraspace. theleftscanwillalwaysstopifitreachesthepartitionelement,whichisthelastelementthismeanstheentirearrayislessthanpartitionvalue. therightscancouldreachthefirstelement,iftheentirearrayisgreaterthanthepartition,andthisneedstobetestedfor,elsethescandoesn'tstop. theouterloopexitswhenthenleftandrightpointerscross.Testingforpointercrossingandouterloopexit shouldoccurbeforeswapping,otherwisetherightpointermaybeswappingalessthanpartitionelementpreviouslyscannedbytheleftpointer. finally,thepartitionelementneedstobeputbetweentheleftandrightpartitions,oncethepointerscross. Atpointercrossing,theleftpointermaybestoppedatthepartitionelement'slastpositioninthearray,andtherightpointernotprogressedpastthe elementjustbeforethelastelement.Thishappenswhenalltheelementsarelessthanthepartition. iftherightpointerischosentoswapwiththepartition,thenanincorrectstateresultswherethelastelementoftheleftarraybecomeslessthanthepartitionelementvalue. iftheleftpointerischosentoswapwiththepartition,thentheleftarraywillbelessthanthepartition,andpartitionwillhaveswappedwithanelementwithvaluegreaterthanthepartitionorthepartitionitself.
en.wikibooks.org/wiki/C_Programming/Print_version
78/118
10/24/13
Thecornercaseofquicksortinga2element outoforderarrayhastobeexamined. Theleftpointerstopsonthefirst outoforderelement.Therightpointerbeginsonthefirst outoforderelement,buttheouterloopexitsbecausethisistheleftmostelement.Thepartitionelementisthenswappedwiththeleftpointer'sfirstelement, andthetwoelementsarenow inorder. Inthecaseofa2element inorderarray,theleftmostpointerskipsthefirstelementwhichislessthanthepartition,andstopsonthepartition.Therightpointerbeginsonthefirstelementandexitsbecauseitisthefirstposition.Thepointershave crossedsotheouterloopexits.Thepartitionswapswithitself,sotheinorderingispreserved. Afterdoingaswap,theleftpointershouldbeincrementedandrightpointerdecremented,sothesamepositionsaren'tscannedagain,becauseanendlessloopcanresult(possiblywhentheleftpointerexitswhentheelementisequaltoorgreater thanthepartition,andtherightelementisequaltothepartitionvalue).Oneimplementation,Sedgewick,startsthepointerswiththeleftpointerminusoneandrightpointer theplusonetheintendedinitialscanpositions,andusethepreincrementandpredecrementoperatorse.g.(++i,i). Solution Onepossiblesolution,canbetoadaptthiswordsortinguseofquicksorttosortintegers.Otherwise,anexercisewouldbetorewritenongenericqsortfunctionsofqsortsimp,partition,andswapforintegers.
/ * *q s o r t s i m p . h * * C r e a t e do n :1 7 / 0 3 / 2 0 1 3 * A u t h o r :a n o n y m o u s * / # i f n d e fQ S O R T S I M P _ H _ # d e f i n eQ S O R T S I M P _ H _ # i n c l u d e< s t d l i b . h > v o i dq s o r t s i m p (v o i d *a ,s i z e _ te l e m _ s z ,i n tl e n ,i n t ( * c m p )( v o i d * , v o i d * )) ; v o i ds h u t d o w n _ q s o r t s i m p ( ) ; # e n d i f/ *Q S O R T S I M P _ H _* / / / / * q s o r t s i m p . c * a u t h o r:a n o n y m o u s * / # i n c l u d e" q s o r t s i m p . h " # i n c l u d e < s t d l i b . h > # i n c l u d e < s t r i n g . h > s t a t i cv o i d*s w a p _ b u f= 0 ; s t a t i ci n tb u f s z=0 ; v o i ds w a p (v o i d *a ,i n ti ,i n tj ,s i z e _ te l e m _ s z ){ i f( i = = j ) r e t u r n ; i f( b u f s z= =0| |b u f s z<e l e m _ s z ){ s w a p _ b u f=r e a l l o c ( s w a p _ b u f ,e l e m _ s z ) ; b u f s z = e l e m _ s z ; } m e m c p y (s w a p _ b u f ,a + i * e l e m _ s z ,e l e m _ s z ) ; m e m c p y (a + i * e l e m _ s z ,a + j * e l e m _ s z ,e l e m _ s z ) ; m e m c p y (a + j * e l e m _ s z ,s w a p _ b u f ,e l e m _ s z ) ; } v o i ds h u t d o w n _ q s o r t s i m p ( ){ i f( s w a p _ b u f ){ f r e e ( s w a p _ b u f ) ; } } i n tp a r t i t i o n (v o i d *a ,s i z e _ te l e m _ s z ,i n tl e n ,i n t( * c m p ) ( v o i d * , v o i d * )){ i n ti=1 ; i n tj=l e n 1 ; v o i d *v=a+j*e l e m _ s z ; f o r ( ; ; ){ w h i l e (( * c m p ) ( a++ + i*e l e m _ s z,v )<0 ) ; w h i l e(( * c m p ) ( v ,a+j*e l e m _ s z )<0)i f( j = = 0 )b r e a k; i f (i > = j ) b r e a k ; s w a p ( a ,i ,j ,e l e m _ s z ) ; } s w a p (a ,i ,l e n 1 ,e l e m _ s z ) ; r e t u r ni ; } v o i dq s o r t s i m p (v o i d *a ,s i z e _ te l e m _ s z ,i n tl e n ,i n t ( * c m p )( v o i d * , v o i d * )){ i f(l e n>2 ){ i n tp=p a r t i t i o n ( a ,e l e m _ s z ,l e n ,c m p ) ;
en.wikibooks.org/wiki/C_Programming/Print_version
79/118
10/24/13
q s o r t s i m p (a ,e l e m _ s z ,p ,c m p ) ; q s o r t s i m p (a + ( p + 1 ) * e l e m _ s z ,e l e m _ s z ,l e n-p1 ,c m p) ; } }
/ / / * N a m e :w o r d s _ q u i c k s o r t . c A u t h o r :a n o n y m o u s V e r s i o n : C o p y r i g h t : D e s c r i p t i o n:q u i c ks o r tt h ew o r d si nm o b yd i c ki nC ,A n s i s t y l e = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / # i n c l u d e< s t d i o . h > # i n c l u d e< s t d l i b . h > # i n c l u d e< c t y p e . h > # i n c l u d e< s t r i n g . h > # i n c l u d e" q s o r t s i m p . h " v o i dp r i n t A r r a y ( c o n s tc h a r *a [ ] ,i n tn ){ i n ti ; f o r ( i = 0 ;i<n ;+ + i ){ i f ( i ! = 0& &i %5= =0 ){ p r i n t f ( " \ n " ) ; } i f( i % 1 0 0 0 0 0 0= = 0 ){ f p r i n t f ( s t d e r r , " p r i n t e d% dw o r d s \ n " ,i ) ; } p r i n t f ( " % s " ,a [ i ] ) ; } p r i n t f ( " \ n " ) ; } c o n s ti n tM A X C H A R S = 2 5 0 ; c h a r* *w o r d l i s t = 0 ; i n tn w o r d s = 0 ; i n tr e m a i n i n g _ b l o c k ; c o n s ts i z e _ tN W O R D S _ P E R _ B L O C K=1 0 0 0 ; / / c o n s tc h a r *s p a c e s = "\ t \ n \ r " ; / / i n l i n ei s s p a c e ( c o n s tc h a rc h ){ / / i n ti = 0 ; / / w h i l e ( s p a c e s [ i ] ! = ' \ 0 ' ){ / / i f ( s p a c e s [ i + + ]= =c h ) / / r e t u r n1 ; / / } / / r e t u r n0 ; / / } v o i df r e e M e m ( ){ i n ti=n w o r d s ; w h i l e ( i>0){ f r e e ( w o r d l i s t [ i ] ) ; } f r e e ( w o r d l i s t ) ; } s t a t i cc h a r*f n a m e = " ~ / D o w n l o a d s / b o o k s / p g 2 7 0 1 m o b y d i c k . t x t " ; v o i dg e t W o r d s ( ){ c h a rb u f f e r [ M A X C H A R S ] ; F I L E *f=f o p e n ( f n a m e , " r " ) ; i n ts t a t e = 0 ; i n tc h ; i n ti ; w h i l e( ( c h = f g e t c ( f ) ) ! = E O F ){ i f( i s a l n u m ( c h )& &s t a t e = = 0 ){ s t a t e = 1 ; i = 0 ; b u f f e r [ i + + ] = c h ; }e l s ei f( i s a l n u m ( c h ) & &i<M A X C H A R S 1 ){ b u f f e r [ i + + ] = c h ; }e l s ei f( s t a t e= =1 ){ s t a t e= 0 ; b u f f e r [ i + + ] =' \ 0 ' ; c h a r *d y n b u f=m a l l o c ( i ) ; i n tj ; f o r ( j = 0 ;j<i ;+ + j ){
en.wikibooks.org/wiki/C_Programming/Print_version
80/118
10/24/13
d y n b u f [ j ]=b u f f e r [ j ] ; } i = 0 ; i f( w o r d l i s t= =0){
w o r d l i s t=c a l l o c ( N W O R D S _ P E R _ B L O C K ,s i z e o f ( c h a r * ) ) ; r e m a i n i n g _ b l o c k=N W O R D S _ P E R _ B L O C K ; }e l s ei f(r e m a i n i n g _ b l o c k= =0 ){ w o r d l i s t=r e a l l o c ( w o r d l i s t ,( N W O R D S _ P E R _ B L O C K+n w o r d s ) *s i z e o f ( c h a r * ) ) ; r e m a i n i n g _ b l o c k=N W O R D S _ P E R _ B L O C K ; f p r i n t f ( s t d e r r , " a l l o c a t e db l o c k% d,n w o r d s=% d \ n " ,r e m a i n i n g _ b l o c k ,n w o r d s ) ; } w o r d l i s t [ n w o r d s + + ] =d y n b u f ; r e m a i n i n g _ b l o c k ; } } f c l o s e ( f ) ; } v o i dt e s t P r i n t A r r a y ( ){ i n ti ; f o r ( i = 0 ;i<n w o r d s ; + + i ){ p r i n t f ( " % s|" ,w o r d l i s t [ i ] ) ; } p u t c h a r ( ' \ n ' ) ; p r i n t f ( " s t o r e d% dw o r d s .\ n " , n w o r d s ) ; } i n tc m p _ s t r _ 1 (v o i d *a ,v o i d* b ){ i n tr=s t r c a s e c m p (* ( ( c h a r * * ) a ) , * ( ( c h a r * * ) b ) ) ; r e t u r nr ; } i n tm a i n ( i n ta r g c ,c h a r *a r g v [ ] ){ i f( a r g c>1 ){ f n a m e=a r g v [ 1 ] ; } g e t W o r d s ( ) ; t e s t P r i n t A r r a y ( ) ; q s o r t s i m p ( w o r d l i s t ,s i z e o f ( c h a r * ) ,n w o r d s ,& c m p _ s t r _ 1 ) ; t e s t P r i n t A r r a y ( ) ; s h u t d o w n _ q s o r t s i m p ( ) ; f r e e M e m ( ) ; p u t s ( " ! ! ! H e l l oW o r l d ! ! ! " ) ;/ *p r i n t s! ! ! H e l l oW o r l d ! ! !* / r e t u r nE X I T _ S U C C E S S ; }
IndepthCideas Arrays
ArraysinCacttostorerelateddataunderasinglevariablenamewithanindex,alsoknownasa subscript .Itiseasiesttothinkofanarrayassimplyalistororderedgroupingforvariablesofthesametype.Assuch,arraysoftenhelpaprogrammer organizecollectionsofdataefficientlyandintuitively. Laterwewillconsidertheconceptofa pointer,fundamentaltoC,whichextendsthenatureofthearray(arraycanbetermedasaconstantpointer).Fornow,wewillconsiderjusttheirdeclarationandtheiruse.
Arrays
Ifwewantan2Darrayofsixintegers(ornumbers),wewriteinC:
i n tn u m b e r s [ 3 ] [ 2 ] ;
ForaSIXcharacterarraycalledletters,
c h a rl e t t e r s [ 6 ] ;
andsoon.
en.wikibooks.org/wiki/C_Programming/Print_version
81/118
10/24/13
Ifwewishtoinitializeaswedeclare,wewrite:
i n tp o i n t [ 6 ] = { 0 , 0 , 1 , 0 , 0 , 0 } ;
Thoughwhenthearrayisinitializedasinthiscase,thearraydimensionmaybeomitted,andthearraywillbeautomaticallysizedtoholdtheinitialdata:
i n tp o i n t [ ] = { 0 , 0 , 1 , 0 , 0 , 0 } ;
Thisisveryusefulinthatthesizeofthearraycanbecontrolledbysimplyaddingorremovinginitializerelementsfromthedefinitionwithouttheneedtoadjustthedimension. Ifthedimensionisspecified,butnotallelementsinthearrayareinitialized,theremainingelementswillcontainavalueof0.Thisisveryuseful,especiallywhenwehaveverylargearrays.
i n tn u m b e r s [ 2 0 0 0 ] = { 2 4 5 } ;
Theaboveexamplesetsthefirstvalueofthearrayto245,andtherestto0. Ifwewanttoaccessavariablestoredinanarray,forexamplewiththeabovedeclaration,thefollowingcodewillstorea1inthevariable x
i n tx ; x=p o i n t [ 2 ] ;
Duringprogramexecution,anoutofboundsarrayaccessdoesnotalwayscausearuntimeerror.Yourprogrammayhappilycontinueafterretrievingavaluefrompoint[1].Toalleviateindexingproblems,thesizeof()expressioniscommonlyusedwhen codingloopsthatprocessarrays.
i n ti x ; s h o r ta n A r r a y [ ] ={3 ,6 ,9 ,1 2 ,1 5} ; f o r( i x = 0 ;i x <( s i z e o f ( a n A r r a y ) / s i z e o f ( s h o r t ) ) ;+ + i x ){ D o S o m e t h i n g W i t h ( " % d " ,a n A r r a y [ i x ]) ; }
Toaccess/modifyavalueinthisarrayweneedtwosubscripts:
c h a rc h ; c h=t w o _ d [ 2 ] [ 4 ] ;
or
t w o _ d [ 0 ] [ 0 ]=' x ' ;
Similarly,amultidimensionalarraycanbeinitializedlikethis:
i n tt w o _ d [ 2 ] [ 3 ]={ {5 ,2 ,1} , {6 ,7 ,8} } ;
en.wikibooks.org/wiki/C_Programming/Print_version
82/118
10/24/13
Theamountofcolumnsmustbeexplicitlystatedhowever,thecompilerwillfindtheappropriateamountofrowsbasedontheinitializerlist. Therearealsoweirdnotationspossible:
i n ta [ 1 0 0 ] ; i n ti=0 ; i f( a [ i ] = = i [ a ] ) { p r i n t f ( " H e l l ow o r l d ! \ n " ) ; }
a[i]andi[a]refertothesamelocation.(ThisisexplainedlaterinthenextChapter.)
Strings
Chasnostringhandlingfacilitiesbuiltinconsequently,stringsaredefinedasarraysofcharacters.Callowsacharacterarraytoberepresentedbyacharacterstringratherthanalistofcharacters, withthenullterminatingcharacterautomaticallyaddedtotheend.Forexample,tostorethestring"Merkkijono",wewouldwrite
c h a rs t r i n g [ ]=" M e r k k i j o n o " ;
String"Merkkijono"storedinmemory
or
c h a rs t r i n g [ ]={ ' M ' ,' e ' ,' r ' ,' k ' ,' k ' ,' i ' ,' j ' ,' o ' ,' n ' ,' o ' ,' \ 0 ' } ;
Whilestringsmayalsospanmultiplelinesbyputtingthebackslashcharacterattheendoftheline,thismethodisdeprecated. Thereisausefullibraryofstringhandlingroutineswhichyoucanusebyincludinganotherheaderfile.
# i n c l u d e< s t r i n g . h > / / n e wh e a d e rf i l e
Thisstandardstringlibrarywillallowvarioustaskstobeperformedonstrings,andisdiscussedintheStringschapter.
Pointersandarrays
A pointerisavaluethatdesignatestheaddress(i.e.,thelocationinmemory),ofsomevalue.Therearefourfundamentalthingsyouneedtoknowaboutpointers: Howtodeclarethem Howtoassigntothem Howtoreferencethevaluetowhichthepointerpoints(knownas dereferencing)and Howtheyrelatetoarrays We'llalsodiscusstherelationshipofpointerswithtextstringsandthemoreadvancedconceptoffunctionpointers. Pointersarevariablesthatholdamemorylocation.Onecanaccessthevalueofthevariablepointedtousingthedereferencingoperator'* '.Pointerscanreferenceanydatatype,evenfunctions. ThevastmajorityofarraysinCaresimplelists,alsocalled"1dimensionalarrays".Wewillbrieflycovermultidimensionalarraysinalaterchapter.
Declaringpointers
Considerthefollowingsnippetofcodewhichdeclarestwopointers:
Pointerapointingvariableb.Note thatbstoresnumber,whereasa storesaddressofbinmemory (1462)
y S t r u c t{ 1 . s t r u c tM _ a N u m b e r 2 . i n t m ; u m 2 3 . f l o a tn ; 4 . } ;
en.wikibooks.org/wiki/C_Programming/Print_version
83/118
10/24/13
5 . J 2 6 . i n t *p ; y S t r u c t*p A n I t e m 7 . s t r u c tM ;
a r 1 a r 2 1 .l o n g * v ,v ; 3 2 . i n t * *p ;
Assigningvaluestopointers
Sofarwe'vediscussedhowtodeclarepointers.Theprocessofassigningvaluestopointersisnext.Toassignapointertheaddressofavariable,the & or'addressof'operatorisused.
i n t m y I n t ; i n t * p P o i n t e r ; s t r u c tM y S t r u c t d v o r a k ; s t r u c tM y S t r u c t * p K e y b o a r d ; p P o i n t e r=& m y I n t ; p K e y b o a r d=& d v o r a k ;
Here,pPointerwillnowreferencemyIntandpKeyboardwillreferencedvorak. Pointerscanalsobeassignedtoreferencedynamicallyallocatedmemory.Themalloc()andcalloc()functionsareoftenwhatareusedtodothis.
# i n c l u d e< s t d l i b . h > / *. . .* / s t r u c tM y S t r u c t* p K e y b o a r d ; / *. . .* / p K e y b o a r d=m a l l o c ( s i z e o f* p K e y b o a r d ) ;
Themallocfunctionreturnsapointertodynamicallyallocatedmemory(orNULLifunsuccessful).ThesizeofthismemorywillbeappropriatelysizedtocontaintheMyStructstructure. Thefollowingisanexampleshowingonepointerbeingassignedtoanotherandofapointerbeingassignedareturnvaluefromafunction.
s t a t i cs t r u c tM y S t r u c tv a l 1 ,v a l 2 ,v a l 3 ,v a l 4 ; s t r u c tM y S t r u c t* A S i l l y F u n c t i o n (i n tb) { s t r u c tM y S t r u c t* m y R e t u r n ; i f( b= =1 )m y R e t u r n=& v a l 1 ; e l s ei f( b = = 2 )m y R e t u r n=& v a l 2 ; e l s ei f( b = = 3 )m y R e t u r n=& v a l 3 ; e l s em y R e t u r n=& v a l 4 ; r e t u r nm y R e t u r n ; } s t r u c tM y S t r u c t* s t r P o i n t e r ; i n t * c ,* d ; i n t j ; c=& j ; / *p o i n t e ra s s i g n e du s i n g&o p e r a t o r* / d=c ; / *a s s i g no n ep o i n t e rt oa n o t h e r * / s t r P o i n t e r=A S i l l y F u n c t i o n (3) ;/ *p o i n t e rr e t u r n e df r o maf u n c t i o n .* /
Whenreturningapointerfromafunction,donotreturnapointerthatpointstoavaluethatislocaltothefunctionorthatisapointertoafunctionargument.Pointerstolocalvariablesbecomeinvalidwhenthefunctionexits.Intheabovefunction,the valuereturnedpointstoastaticvariable.Returningapointertodynamicallyallocatedmemoryisalsovalid.
en.wikibooks.org/wiki/C_Programming/Print_version
84/118
10/24/13
Pointerdereferencing
Toaccessavaluetowhichapointerpoints,the * operatorisused.Anotheroperator,the > operatorisusedinconjunctionwithpointerstostructures.Here'sashortexample.
i n t c ,d ; i n t * p j ; s t r u c tM y S t r u c ta s t r u c t ; s t r u c tM y S t r u c t* b b ; c =1 0 ; p j =& c ; d =* p j ; p j =& d ; * p j=1 2 ; / *p jp o i n t st oc* / / *di sa s s i g n e dt h ev a l u et ow h i c hp jp o i n t s ,1 0* / / *n o wp o i n t st od* / / *di sn o w1 2* / Thepointerp pointstothevariablea .
Theexpression b b > m _ a N u m b e r isentirelyequivalentto ( * b b ) . m _ a N u m b e r .Theybothaccessthe m _ a N u m b e r elementofthestructurepointedtoby b b .Thereisonemorewayofdereferencingapointer,whichwillbediscussedinthefollowingsection. Whendereferencingapointerthatpointstoaninvalidmemorylocation,anerroroftenoccurswhichresultsintheprogramterminating.Theerrorisoftenreportedasasegmentationerror.Acommoncauseofthisisfailuretoinitializeapointerbefore tryingtodereferenceit. Cisknownforgivingyoujustenoughropetohangyourself,andpointerdereferencingisaprimeexample.Youarequitefreetowritecodethataccessesmemoryoutsidethatwhichyouhaveexplicitlyrequestedfromthesystem.Andmanytimes,that memorymayappearasavailabletoyourprogramduetothevagariesofsystemmemoryallocation.However,evenif99executionsallowyourprogramtorunwithoutfault,that100thexecutionmaybethetimewhenyour"memorypilfering"iscaughtby thesystemandtheprogramfails.Becarefultoensurethatyourpointeroffsetsarewithintheboundsofallocatedmemory! Thedeclaration v o i d* s o m e P o i n t e r ; isusedtodeclareapointerofsomenonspecifiedtype.Youcanassignavaluetoavoidpointer,butyoumustcastthevariabletopointtosomespecifiedtypebeforeyoucandereferenceit.Pointerarithmeticisalsonot validwith v o i d* pointers.
PointersandArrays
Uptonow,we'vecarefullybeenavoidingdiscussingarraysinthecontextofpointers.Theinteractionofpointersandarrayscanbeconfusingbutherearetwofundamentalstatementsaboutit: Avariabledeclaredasanarrayofsometypeactsasapointertothattype.Whenusedbyitself,itpointstothefirstelementofthearray. Apointercanbeindexedlikeanarrayname. Thefirstcaseoftenisseentooccurwhenanarrayispassedasanargumenttoafunction.Thefunctiondeclarestheparameterasapointer,buttheactualargumentmaybethenameofanarray.Thesecondcaseoftenoccurswhenaccessing dynamicallyallocatedmemory.Let'slookatexamplesofeach.Inthefollowingcode,thecalltocalloc()effectivelyallocatesanarrayofstructMyStructitems.
f l o a tK r a z y F u n c t i o n (s t r u c tM y S t r u c t* p a r m 1 ,i n tp 1 s i z e ,i n tb b) { i n ti x ;/ / d e c l a r i n ga ni n t e g e rv a r i a b l e / / f o r( i x = 0 ;i x < p 1 s i z e ;i x + + ){ i f( p a r m 1 [ i x ] . m _ a N u m b e r= =b b) r e t u r np a r m 1 [ i x ] . n u m 2 ; } r e t u r n0 . 0 f ; } / *. . .* / s t r u c tM y S t r u c tm y A r r a y [ 4 ] ; # d e f i n eM Y _ A R R A Y _ S I Z E( s i z e o f ( m y A r r a y ) / s i z e o f ( * m y A r r a y ) ) f l o a tv 3 ; s t r u c tM y S t r u c t* s e c o n d A r r a y ; i n t s o m e S i z e ; i n t i x ; / *i n i t i a l i z a t i o no fm y A r r a y. . .* / v 3=K r a z y F u n c t i o n (m y A r r a y ,M Y _ A R R A Y _ S I Z E ,4) ; / *. . .* / s e c o n d A r r a y=c a l l o c (s o m e S i z e ,s i z e o f ( m y A r r a y )) ; f o r( i x = 0 ;i x < s o m e S i z e ;i x + + ){ s e c o n d A r r a y [ i x ] . m _ a N u m b e r=i x* 2 ; s e c o n d A r r a y [ i x ] . n u m 2=. 3 0 4*i x*i x ; }
/ *t w oe q u i v a l e n tf u n c t i o nd e f i n i t i o n s* / i n tL i t t l e F u n c t i o n (i n t* p a r a m N) ;
en.wikibooks.org/wiki/C_Programming/Print_version
85/118
10/24/13
i n tL i t t l e F u n c t i o n (i n tp a r a m N [ ]) ;
Let'slookataslightlydifferentproblem.Wewanttohaveatwodimensionalarray,butwedon'tneedtohavealltherowsthesamelength.Whatwedoisdeclareanarrayofpointers.ThesecondlinebelowdeclaresAasanarrayofpointers.Eachpointer pointstoafloat.Here'ssomeapplicablecode:
f l o a t l i n e a r A [ 3 0 ] ; f l o a t* A [ 6 ] ; A [ 0 ]=l i n e a r A ; A [ 1 ]=l i n e a r A+5 ; A [ 2 ]=l i n e a r A+1 1 ; A [ 3 ]=l i n e a r A+1 5 ; A [ 4 ]=l i n e a r A+2 1 ; A [ 5 ]=l i n e a r A+2 5 ; A [ 3 ] [ 2 ]=3 . 6 6 ; A [ 3 ] [ 3 ]=1 . 4 4 ; / * 5-0=5e l e m e n t si nr o w * / / *1 1-5=6e l e m e n t si nr o w * / / *1 5-1 1=4e l e m e n t si nr o w* / / *2 1-1 5=6e l e m e n t s * / / *2 5-2 1=4e l e m e n t s * / / *3 0-2 5=5e l e m e n t s * / / *a s s i g n s3 . 6 6t ol i n e a r A [ 1 7 ] ; * / / *r e f e r st ol i n e a r A [ 1 2 ] ; n e g a t i v ei n d i c e sa r es o m e t i m e su s e f u l .B u ta v o i du s i n gt h e ma sm u c ha sp o s s i b l e .* /
PointersinFunctionArguments
Oftenweneedtoinvokeafunctionwithanargumentthatisitselfapointer.Inmanyinstances,thevariableisitselfaparameterforthecurrentfunctionandmaybeapointertosometypeofstructure.Theampersandcharacterisnotneededinthis circumstancetoobtainapointervalue,asthevariableisitselfapointer.Intheexamplebelow,thevariable p S t r u c t ,apointer,isaparametertofunction F u n c t T w o , andispassedasanargumentto F u n c t O n e .Thesecondparameterto F u n c t O n e isanint.Sincein function F u n c t T w o ,m V a l u e isapointertoanint,thepointermustfirstbedereferencedusingthe*operator,hencethesecondargumentinthecallis * m V a l u e .Thethirdparametertofunction F u n c t O n e isapointertoalong.Since p A A isitselfapointertoalong, noampersandisneededwhenitisusedasthethirdargumenttothefunction.
i n tF u n c t O n e (s t r u c tS o m e S t r u c t* p V a l u e ,i n ti V a l u e ,l o n g* l V a l u e) {
en.wikibooks.org/wiki/C_Programming/Print_version
86/118
10/24/13
/ * d os o m es t u f f. . .* / r e t u r n0 ; } i n tF u n c t T w o (s t r u c ts o m e S t r u c t* p S t r u c t ,i n t* m V a l u e) { i n tj ; l o n g A n A r r a y [ 2 5 ] ; l o n g* p A A ; p A A=& A n A r r a y [ 1 3 ] ; j=F u n c t O n e (p S t r u c t ,* m V a l u e ,p A A) ; r e t u r nj ; }
PointersandTextStrings
Historically,textstringsinChavebeenimplementedasarraysofcharacters,withthelastbyteinthestringbeingazero,orthenullcharacter'\0'.MostCimplementationscomewithastandardlibraryoffunctionsformanipulatingstrings.Manyofthe morecommonlyusedfunctionsexpectthestringstobenullterminatedstringsofcharacters.TousethesefunctionsrequirestheinclusionofthestandardCheaderfile"string.h". Astaticallydeclared,initializedstringwouldlooksimilartothefollowing:
s t a t i cc o n s tc h a r* m y F o r m a t=" T o t a lA m o u n tD u e :% d " ;
Thevariable m y F o r m a t canbeviewedasanarrayof21characters.Thereisanimpliednullcharacter('\0')tackedontotheendofthestringafterthe'd'asthe21stiteminthearray.Youcanalsoinitializetheindividualcharactersofthearrayasfollows:
s t a t i cc o n s tc h a rm y F l o w e r [ ]={' P ' ,' e ' ,' t ' ,' u ' ,' n ' ,' i ' ,' a ' ,' \ 0 '} ;
Aninitializedarrayofstringswouldtypicallybedoneasfollows:
s t a t i cc o n s tc h a r* m y C o l o r s [ ]={ " R e d " ," O r a n g e " ," Y e l l o w " ," G r e e n " ," B l u e " ," V i o l e t "} ;
Theinitilizationofanespeciallylongstringcanbesplitacrosslinesofsourcecodeasfollows.
s t a t i cc h a r* l o n g S t r i n g=" H e l l o .M yn a m ei sR u d o l p ha n dIw o r ka sar e i n d e e r" " a r o u n dC h r i s t m a st i m eu pa tt h eN o r t hP o l e . M yb o s si sar e a l l ys w e l lg u y . " "H el i k e st og i v ee v e r y b o d yg i f t s . " ;
Thelibraryfunctionsthatareusedwithstringsarediscussedinalaterchapter.
PointerstoFunctions
Calsoallowsyoutocreatepointerstofunctions.Pointerstofunctionscangetrathermessy.Declaringatypedeftoafunctionpointergenerallyclarifiesthecode.Here'sanexamplethatusesafunctionpointer,andavoid*pointertoimplementwhat's knownasacallback.The D o S o m e t h i n g N i c e functioninvokesacallersuppliedfunction T a l k J i v e withcallerdata.Notethat D o S o m e t h i n g N i c e reallydoesn'tknowanythingaboutwhat d a t a P o i n t e r refersto.
t y p e d e f i n t( * M y F u n c t i o n T y p e ) (i n t ,v o i d* ) ; # d e f i n eT H E _ B I G G E S T1 0 0 i n tD o S o m e t h i n g N i c e (i n ta V a r i a b l e ,M y F u n c t i o n T y p ea F u n c t i o n ,v o i d* d a t a P o i n t e r) { i n tr v=0 ; i f( a V a r i a b l e<T H E _ B I G G E S T ){ / *i n v o k ef u n c t i o nt h r o u g hf u n c t i o np o i n t e r( o l ds t y l e )* / r v=( * a F u n c t i o n ) ( a V a r i a b l e ,d a t a P o i n t e r) ; }e l s e{ / *i n v o k ef u n c t i o nt h r o u g hf u n c t i o np o i n t e r( n e ws t y l e )* / r v=a F u n c t i o n ( a V a r i a b l e ,d a t a P o i n t e r) ; } ; r e t u r nr v ; } t y p e d e fs t r u c t{ i n t c o l o r S p e c ; c h a r * p h r a s e ; }D a t a I N e e d ; i n tT a l k J i v e (i n tm y N u m b e r ,v o i d* s o m e S t u f f) { / *r e c a s tv o i d*t op o i n t e rt y p es p e c i f i c a l l yn e e d e df o rt h i sf u n c t i o n* / D a t a I N e e d* m y D a t a=s o m e S t u f f ; / *t a l kj i v e .* / r e t u r n5 ; / *at y p e d e ff o raf u n c t i o np o i n t e r* /
en.wikibooks.org/wiki/C_Programming/Print_version
87/118
10/24/13
} s t a t i cD a t a I N e e d s i l l y S t u f f={B L U E ," W h a t c h at a l k i n' b o u tW i l l i s ? "} ; / *. . .* / D o S o m e t h i n g N i c e (4 1 ,& T a l k J i v e , & s i l l y S t u f f) ;
SomeversionsofCmaynotrequireanampersandprecedingthe T a l k J i v e argumentinthe D o S o m e t h i n g N i c e call.Someimplementationsmayrequirespecificallycastingtheargumenttothe M y F u n c t i o n T y p e type,eventhoughthefunctionsignatureexacly matchesthatofthetypedef. FunctionpointerscanbeusefulforimplementingaformofpolymorphisminC.Firstonedeclaresastructurehavingaselementsfunctionpointersforthevariousoperationstothatcanbespecifiedpolymorphically.Asecondbaseobjectstructure containingapointertothepreviousstructureisalsodeclared.Aclassisdefinedbyextendingthesecondstructurewiththedataspecificfortheclass,andstaticvariableofthetypeofthefirststructure,containingtheaddressesofthefunctionsthatare associatedwiththeclass.ThistypeofpolymorphismisusedinthestandardlibrarywhenfileI/Ofunctionsarecalled. AsimilarmechanismcanalsobeusedforimplementingastatemachineinC.Astructureisdefinedwhichcontainsfunctionpointersforhandlingeventsthatmayoccurwithinstate,andforfunctionstobeinvokeduponentrytoandexitfromthestate.An instanceofthisstructurecorrespondstoastate.Eachstateisinitializedwithpointerstofunctionsappropriateforthestate.Thecurrentstateofthestatemachineisineffectapointertooneofthesestates.Changingthevalueofthecurrentstatepointer effectivelychangesthecurrentstate.Whensomeeventoccurs,theappropriatefunctioniscalledthroughafunctionpointerinthecurrentstate.
PracticaluseoffunctionpointersinC
Functionpointersaremainlyusedtoreducethecomplexityofswitchstatement.Examplewithswitchstatement:
# i n c l u d e< s t d i o . h > i n ta d d ( i n ta ,i n tb ) ; i n ts u b ( i n ta ,i n tb ) ; i n tm u l ( i n ta ,i n tb ) ; i n td i v ( i n ta ,i n tb ) ; i n tm a i n ( ) { i n ti ,r e s u l t ; i n ta = 1 0 ; i n tb = 5 ; p r i n t f ( " E n t e rt h ev a l u eb e t w e e n0a n d3:" ) ; s c a n f ( " % d " , & i ) ; s w i t c h ( i ) { c a s e0 : r e s u l t=a d d ( a , b ) ;b r e a k ; c a s e1 : r e s u l t=s u b ( a , b ) ;b r e a k ; c a s e2 : r e s u l t=m u l ( a , b ) ;b r e a k ; c a s e3 : r e s u l t=d i v ( a , b ) ;b r e a k ; } } i n ta d d ( i n ti ,i n tj ) { r e t u r n( i + j ) ; } i n ts u b ( i n ti ,i n tj ) { r e t u r n( i j ) ; } i n tm u l ( i n ti ,i n tj ) { r e t u r n( i * j ) ; } i n td i v ( i n ti ,i n tj ) { r e t u r n( i / j ) ; }
Withoutusingaswitchstatement:
# i n c l u d e< s t d i o . h > i n ta d d ( i n ta ,i n tb ) ; i n ts u b ( i n ta ,i n tb ) ; i n tm u l ( i n ta ,i n tb ) ; i n td i v ( i n ta ,i n tb ) ; i n t( * o p e r [ 4 ] ) ( i n ta ,i n tb )={ a d d ,s u b ,m u l ,d i v } ; i n tm a i n ( ) { i n ti , r e s u l t ; i n ta = 1 0 ; i n tb = 5 ; p r i n t f ( " E n t e rt h ev a l u eb e t w e e n0a n d3:" ) ; s c a n f ( " % d " , & i ) ; r e s u l t=o p e r [ i ] ( a , b ) ; } i n ta d d ( i n ti ,i n tj ) { r e t u r n( i + j ) ; } i n ts u b ( i n ti ,i n tj ) {
en.wikibooks.org/wiki/C_Programming/Print_version
88/118
10/24/13
r e t u r n( i j ) ; } i n tm u l ( i n ti ,i n tj ) { r e t u r n( i * j ) ; } i n td i v ( i n ti ,i n tj ) { r e t u r n( i / j ) ; }
Functionpointersmaybeusedtocreateastructmemberfunction:
t y p e d e fs t r u c t { i n t( * o p e n ) ( v o i d ) ; v o i d( * c l o s e ) ( v o i d ) ; i n t( * r e g i s t e r ) ( v o i d ) ; }d e v i c e ; i n tm y _ d e v i c e _ o p e n ( v o i d ) { / *. . .* / } v o i dm y _ d e v i c e _ c l o s e ( v o i d ) { / *. . .* / } v o i dr e g i s t e r _ d e v i c e ( v o i d ) { / *. . .* / } d e v i c ec r e a t e ( v o i d ) { d e v i c em y _ d e v i c e ; m y _ d e v i c e . o p e n=m y _ d e v i c e _ o p e n ; m y _ d e v i c e . c l o s e=m y _ d e v i c e _ c l o s e ; m y _ d e v i c e . r e g i s t e r=r e g i s t e r _ d e v i c e ; m y _ d e v i c e . r e g i s t e r ( ) ; r e t u r nm y _ d e v i c e ; }
Usetoimplementthispointer(followingcodemustbeplacedinlibrary).
s t a t i cs t r u c td e v i c e _ d a t a { / *. . .h e r eg o e sd a t ao fs t r u c t u r e. . .* / } ; s t a t i cs t r u c td e v i c e _ d a t ao b j ; t y p e d e fs t r u c t { i n t( * o p e n ) ( v o i d ) ; v o i d( * c l o s e ) ( v o i d ) ; i n t( * r e g i s t e r ) ( v o i d ) ; }d e v i c e ; s t a t i cs t r u c td e v i c e _ d a t ac r e a t e _ d e v i c e _ d a t a ( v o i d ) { s t r u c td e v i c e _ d a t am y _ d e v i c e _ d a t a ; / *. . .h e r eg o e sc o n s t r u c t o r. . .* / r e t u r nm y _ d e v i c e _ d a t a ; } / *h e r eIo m i tt h em y _ d e v i c e _ o p e n ,m y _ d e v i c e _ c l o s ea n dr e g i s t e r _ d e v i c ef u n c t i o n s* / d e v i c ec r e a t e _ d e v i c e ( v o i d ) { d e v i c em y _ d e v i c e ; m y _ d e v i c e . o p e n=m y _ d e v i c e _ o p e n ; m y _ d e v i c e . c l o s e=m y _ d e v i c e _ c l o s e ; m y _ d e v i c e . r e g i s t e r=r e g i s t e r _ d e v i c e ; m y _ d e v i c e . r e g i s t e r ( ) ; r e t u r nm y _ d e v i c e ; }
Examplesofpointerconstructs
Belowaresomeexampleconstructswhichmayaidincreatingyourpointer.
en.wikibooks.org/wiki/C_Programming/Print_version
89/118
10/24/13
i n ti ; / /i n t e g e rv a r i a b l e' i ' i n t* p ; / /p o i n t e r' p 't oa ni n t e g e r i n ta [ ] ; / /a r r a y' a 'o fi n t e g e r s i n tf ( ) ; / /f u n c t i o n' f 'w i t hr e t u r nv a l u eo ft y p ei n t e g e r i n t* * p p ; / /p o i n t e r' p p 't oap o i n t e rt oa ni n t e g e r i n t( * p a ) [ ] ; / /p o i n t e r' p a 't oa na r r a yo fi n t e g e r i n t( * p f ) ( ) ; / /p o i n t e r' p f 't oaf u n c t i o nw i t hr e t u r nv a l u ei n t e g e r i n t* a p [ ] ; / /a r r a y' a p 'o fp o i n t e r st oa ni n t e g e r i n t* f p ( ) ; / /f u n c t i o n' f p 'w h i c hr e t u r n sap o i n t e rt oa ni n t e g e r i n t* * * p p p ; / /p o i n t e r' p p p 't oap o i n t e rt oap o i n t e rt oa ni n t e g e r i n t( * * p p a ) [ ] ;/ /p o i n t e r' p p a 't oap o i n t e rt oa na r r a yo fi n t e g e r s i n t( * * p p f ) ( ) ;/ /p o i n t e r' p p f 't oap o i n t e rt oaf u n c t i o nw i t hr e t u r nv a l u eo ft y p ei n t e g e r i n t* ( * p a p ) [ ] ;/ /p o i n t e r' p a p 't oa na r r a yo fp o i n t e r st oa ni n t e g e r i n t* ( * p f p ) ( ) ;/ /p o i n t e r' p f p 't of u n c t i o nw i t hr e t u r nv a l u eo ft y p ep o i n t e rt oa ni n t e g e r i n t* * a p p [ ] ; / /a r r a yo fp o i n t e r s' a p p 't h a tp o i n tt op o i n t e r st oi n t e g e rv a l u e s i n t( * a p a [ ] ) [ ] ; / /a r r a yo fp o i n t e r s' a p a 't oa r r a y so fi n t e g e r s i n t( * a p f [ ] ) ( ) ; / /a r r a yo fp o i n t e r s' a p f 't of u n c t i o n sw i t hr e t u r nv a l u e so ft y p ei n t e g e r i n t* * * f p p ( ) ; / /f u n c t i o n' f p p 'w h i c hr e t u r n sap o i n t e rt oap o i n t e rt oap o i n t e rt oa ni n t i n t( * f p a ( ) ) [ ] ; / /f u n c t i o n' f p a 'w i t hr e t u r nv a l u eo fap o i n t e rt oa r r a yo fi n t e g e r s i n t( * f p f ( ) ) ( ) ; / /f u n c t i o n' f p f 'w i t hr e t u r nv a l u eo fap o i n t e rt of u n c t i o nw h i c hr e t u r n sa ni n t e g e r
sizeof
Thesizeofoperatorisoftenusedtorefertothesizeofastaticarraydeclaredearlierinthesamefunction. Tofindtheendofanarray(examplefromwikipedia:Bufferoverflow):
/ *b e t t e r . c-d e m o n s t r a t e so n em e t h o do ff i x i n gt h ep r o b l e m* / # i n c l u d e< s t d i o . h > # i n c l u d e< s t r i n g . h > i n tm a i n ( i n ta r g c ,c h a r* a r g v [ ] ) { c h a rb u f f e r [ 1 0 ] ; i f( a r g c<2 ) { f p r i n t f ( s t d e r r ," U S A G E :% ss t r i n g \ n " ,a r g v [ 0 ] ) ; r e t u r n1 ; } s t r n c p y ( b u f f e r ,a r g v [ 1 ] ,s i z e o f ( b u f f e r ) ) ; b u f f e r [ s i z e o f ( b u f f e r )-1 ]=' \ 0 ' ; r e t u r n0 ; }
Toiterateovereveryelementofanarray,use
# d e f i n eN U M _ E L E M ( x )( s i z e o f( x )/s i z e o f( * ( x ) ) ) f o r (i=0 ;i<N U M _ E L E M ( a r r a y ) ;i + +) { / *d os o m e t h i n gw i t ha r r a y [ i ]* / ; }
en.wikibooks.org/wiki/C_Programming/Print_version
90/118
10/24/13
i n tm a i n ( i n ta r g c ,c h a r* a r g v [ ] ) { i n tl e f t _ a r r a y [ ]={1 ,2 ,3} ; i n tr i g h t _ a r r a y [ ]={1 0 ,9 ,8 ,7 ,6 ,5 ,4 ,3 ,2 ,1} ; i n tt h e _ s u m=s u m (l e f t _ a r r a y) ; p r i n t f (" t h es u mo fl e f t _ a r r a yi s :% d " ,t h e _ s u m) ; t h e _ s u m=s u m (r i g h t _ a r r a y) ; p r i n t f (" t h es u mo fr i g h t _ a r r a yi s :% d " ,t h e _ s u m) ; r e t u r n0 ; }
ExternalLinks
CReferenceCard(ANSI)(http://www.digilife.be/quickreferences/QRC/C%20Reference%20Card%20(ANSI)%202.2.pdf) "CommonPointerPitfalls"(http://www.cs.cf.ac.uk/Dave/C/node10.html#SECTION001080000000000000000)byDaveMarshall "Furtherinsightsintosize_t"(http://www.embedded.com/columns/programmingpointers/201803576)byDanSaks2007 "PointerFunwithBinky"
Memorymanagement
InC,youhavealreadyconsideredcreatingvariablesforuseintheprogram.Youhavecreatedsomearraysforuse,butyoumayhavealreadynoticedsomelimitations: thesizeofthearraymustbeknownbeforehand thesizeofthearraycannotbechangedinthedurationofyourprogram DynamicmemoryallocationinCisawayofcircumventingtheseproblems.
EXAMPLE
# i n c l u d e< s t d l i b . h > v o i d* c a l l o c ( s i z e _ tn m e m b ,s i z e _ ts i z e ) ; v o i df r e e ( v o i d* p t r ) ; v o i d* m a l l o c ( s i z e _ ts i z e ) ; v o i d* r e a l l o c ( v o i d* p t r ,s i z e _ ts i z e ) ;
en.wikibooks.org/wiki/C_Programming/Print_version
91/118
10/24/13
Recall a r r a y canbeconsideredapointerwhichweuseasanarray.Wespecifythelengthofthisarrayis10 i n t s.After a r r a y [ 0 ] ,nineotherintegershavespacetobestoredconsecutively. Sometimesitisnotknownatthetimetheprogramiswrittenhowmuchmemorywillbeneededforsomedata.Inthiscasewewouldwanttodynamicallyallocaterequiredmemoryaftertheprogramhasstartedexecuting.Todothisweonlyneedto declareapointer,andinvoke m a l l o c whenwewishtomakespacefortheelementsinourarray, or,wecantell m a l l o c tomakespacewhenwefirstinitializethearray.Eitherwayisacceptableanduseful. Wealsoneedtoknowhowmuchaninttakesupinmemoryinordertomakeroomforitfortunatelythisisnotdifficult,wecanuseC'sbuiltin s i z e o f operator.Forexample,if s i z e o f ( i n t ) yields4,thenone i n t takesup4bytes.Naturally, 2 * s i z e o f ( i n t ) ishow muchmemoryweneedfor2 i n t s,andsoon. Sohowdowe m a l l o c anarrayoften i n t slikebefore?Ifwewishtodeclareandmakeroominonehit,wecansimplysay
i n t* a r r a y=m a l l o c ( 1 0 * s i z e o f ( i n t ) ) ;
Weonlyneedtodeclarethepointer m a l l o c givesussomespacetostorethe10 i n t s,andreturnsthepointertothefirstelement,whichisassignedtothatpointer. Importantnote! m a l l o c does not initializethearraythismeansthatthearraymaycontainrandomorunexpectedvalues!Likecreatingarrayswithoutdynamicallocation,theprogrammermustinitializethearraywithsensiblevaluesbeforeusingit.Make sureyoudoso,too.(Seelaterthefunction m e m s e t forasimplemethod.) Itisnotnecessarytoimmediatelycall m a l l o c afterdeclaringapointerfortheallocatedmemory.Oftenanumberofstatementsexistbetweenthedeclarationandthecallto m a l l o c ,asfollows:
i n t* a r r a y=N U L L ; p r i n t f ( " H e l l oW o r l d ! ! ! " ) ; / *m o r es t a t e m e n t s* / a r r a y=m a l l o c ( 1 0 * s i z e o f ( i n t ) ) ;/ *d e l a y e da l l o c a t i o n* / / *u s et h ea r r a y* /
Errorchecking
Whenwewanttouse m a l l o c ,wehavetobemindfulthatthepoolofmemoryavailabletotheprogrammeris finite.Assuch,wecanconceivablyrunoutofmemory!Inthiscase, m a l l o c willreturn N U L L .Inordertostoptheprogramcrashingfromhavingno morememorytouse,oneshouldalwayscheckthatmallochasnotreturned N U L L beforeattemptingtousethememorywecandothisby
i n t* p t=m a l l o c ( 3*s i z e o f ( i n t ) ) ; i f ( p t= =N U L L ) { f p r i n t f ( s t d e r r ," O u to fm e m o r y ,e x i t i n g \ n " ) ; e x i t ( 1 ) ; }
Thec a l l o c function
The c a l l o c functionallocatesspaceforanarrayofitemsandinitilizesthememorytozeros.Thecall m A r r a y=c a l l o c (c o u n t ,s i z e o f ( s t r u c tV ) ) allocates c o u n t objects,eachofwhosesizeissufficienttocontainaninstanceofthestructure s t r u c tV .Thespaceis initializedtoallbitszero.Thefunctionreturnseitherapointertotheallocatedmemoryor,iftheallocationfails, N U L L .
Ther e a l l o c function
v o i d*r e a l l o c(v o i d*p t r ,s i z e _ ts i z e) ;
en.wikibooks.org/wiki/C_Programming/Print_version
92/118
10/24/13
The r e a l l o c functionchangesthesizeoftheobjectpointedtoby p t r tothesizespecifiedby s i z e .Thecontentsoftheobjectshallbeunchangeduptothelesserofthenewandoldsizes.Ifthenewsizeislarger,thevalueofthenewlyallocatedportionof theobjectisindeterminate.If p t r isanullpointer,the r e a l l o c functionbehaveslikethe m a l l o c functionforthespecifiedsize.Otherwise,if p t r doesnotmatchapointerearlierreturnedbythe c a l l o c , m a l l o c ,or r e a l l o c function,orifthespacehasbeen deallocatedbyacalltothe f r e e or r e a l l o c function,thebehaviorisundefined.Ifthespacecannotbeallocated,theobjectpointedtoby p t r isunchanged.If s i z e iszeroand p t r isnotanullpointer,theobjectpointedtoisfreed.The r e a l l o c functionreturns eitheranullpointerorapointertothepossiblymovedallocatedobject.
Thef r e e function
Memorythathasbeenallocatedusing m a l l o c , r e a l l o c ,or c a l l o c mustbereleasedbacktothesystemmemorypoolonceitisnolongerneeded.Thisisdonetoavoidperpetuallyallocatingmoreandmorememory,whichcouldresultinaneventualmemory allocationfailure.Memorythatisnotreleasedwith f r e e ishoweverreleasedwhenthecurrentprogramterminatesonmostoperatingsystems.Callsto f r e e areasinthefollowingexample.
i n t* m y S t u f f=m a l l o c (2 0*s i z e o f ( i n t ) ) ; i f( m y S t u f f! =N U L L ) { / *m o r es t a t e m e n t sh e r e* / / *t i m et or e l e a s em y S t u f f* / f r e e (m y S t u f f) ; }
freewithrecursivedatastructures
Itshouldbenotedthat f r e e isneitherintelligentnorrecursive.Thefollowingcodethatdependsontherecursiveapplicationoffreetotheinternalvariablesofastructdoesnotwork.
t y p e d e fs t r u c tB S T N o d e { i n tv a l u e ; s t r u c tB S T N o d e *l e f t ; s t r u c tB S T N o d e *r i g h t ; }B S T N o d e ; / /L a t e r :. . . B S T N o d e *t e m p=( B S T N o d e * )c a l l o c ( 1 ,s i z e o f ( B S T N o d e ) ) ; t e m p > l e f t=( B S T N o d e * )c a l l o c ( 1 ,s i z e o f ( B S T N o d e ) ) ; / /L a t e r :. . . f r e e ( t e m p ) ;/ /W R O N G !d o n ' td ot h i s !
Don'tfreeundefinedpointers
Furthermore,using f r e e whenthepointerinquestionwasneverallocatedinthefirstplaceoftencrashesorleadstomysteriousbugsfurtheralong. Toavoidthisproblem,alwaysinitializepointerswhentheyaredeclared.Eitheruse m a l l o c atthepointtheyaredeclared(asinmostexamplesinthischapter),orsetthemto N U L L whentheyaredeclared(asinthe"delayedallocation"exampleinthis chapter). [17]
References
1. Severalprogrammersrecommend"usespacesforindentation.Donotusetabsinyourcode.Youshouldsetyoureditortoemitspaceswhenyouhitthetabkey."[1](http://googlestyleguide.googlecode.com/svn/trunk/cppguide.xml)[2] (http://www.jwz.org/doc/tabsvsspaces.html)Otherprogrammersdisagree.[3](http://diagrammesmodernes.blogspot.com/2006/04/tabversusspaces.html)[4](http://www.derkarl.org/why_to_tabs.html)Regardlessofwhetheryoupreferspacesor tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5](http://www.oualline.com/vimcook.html#drawing) 3. [http://lxr.linux.no/#linux+v2.6.31/Documentation/CodingStyleLinuxKernelcodingstandard 4. "CodingConventionsforC++andJava"(http://www.macadamian.com/index.php?option=com_content&task=view&id=34&Itemid=37)"alltheblockcommentsillustratedinthisdocumenthavenoprettystarsontherightsideoftheblockcomment. Thisdeliberatechoicewasmadebecausealigningthoseprettystarsisalargewasteoftimeanddiscouragesthemaintenanceofinlinecomments.", 5. wiki:BigBlocksOfAsterisks,"Codecraft"(http://books.google.com/books? id=i4zCzpkrt4sC&pg=PA82&lpg=PA82&dq=programming+comment+block+waste+time+lining+up&source=bl&ots=TUpTMIHBnh&sig=NeZm23WPmvnw2aKMnIRUeQoHmJg&hl=en&ei=pri3SevGIYGyNMn9jd4K&sa=X&oi=book_result&resnum=8&ct=result) byPeteGoodliffepage82,Falvotech"CProgrammingStyleGuide"(http://www.falvotech.com/content/publications/conventions/c/),FedoraDirectoryServerCodingStyle(http://directory.fedoraproject.org/wiki/Coding_Style)
Strings
A stringinCismerelyanarrayofcharacters.Thelengthofastringisdeterminedbyaterminatingnullcharacter: ' \ 0 ' .So,astringwiththecontents,say, " a b c " hasfourcharacters: ' a ' , ' b ' , ' c ' ,andtheterminatingnullcharacter. Theterminatingnullcharacterhasthevaluezero.
en.wikibooks.org/wiki/C_Programming/Print_version
93/118
10/24/13
Syntax
InC,stringconstants(literals)aresurroundedbydoublequotes("),e.g."Helloworld!"andarecompiledtoanarrayofthespecified c h a r valueswithanadditionalnullterminatingcharacter(0valued)codetomarktheendofthestring.Thetypeofastring constantis c h a r* . Stringliteralsmaynotdirectlyinthesourcecodecontainembeddednewlinesorothercontrolcharacters,orsomeothercharactersofspecialmeaninginstring. Toincludesuchcharactersinastring,thebackslashescapesmaybeused,likethis: Escape Meaning
\ \ \ " \ ' \ n \ r \ b \ t \ f \ a \ v \ ? \ nnn \ x hh
Literalbackslash Doublequote Singlequote Newline(linefeed) Carriagereturn Backspace Horizontaltab Formfeed Alert(bell) Verticaltab Questionmark(usedtoescapetrigraphs) Characterwithoctalvalue nnn Characterwithhexadecimalvalue hh
Widecharacterstrings
Csupportswidecharacterstrings,definedasarraysofthetype w c h a r _ t ,16bit(atleast)values.TheyarewrittenwithanLbeforethestringlikethis
w c h a r _ t* p=L " H e l l o w o r l d ! " ;
Characterencodings
Whatcharacterencodingthe c h a r and w c h a r _ t representisnotspecifiedbytheCstandard,exceptthatthevalue0x00and0x0000specifytheendofthestringandnotacharacter.Ittheinputandoutputcodewhicharedirectlyaffectedbythecharacter encoding.Othercodeshouldnotbetooaffected.Theeditorshouldalsobeabletohandletheencodingifstringsshallbeabletowritteninthesourcecode. Therearethreemajortypesofencodings: Onebytepercharacter.NormallybasedonASCII.Thereisalimitof255differentcharactersplusthezeroterminationcharacter. Variablelength c h a r strings,whichallowsmanymorethan255differentcharacters.Suchstringsarewrittenasnormal c h a r basedarrays.TheseencodingsarenormallyASCIIbasedandexamplesareUTF8orShiftJIS. Widecharacterstrings.Theyarearraysof w c h a r _ t values.UTF16isthemostcommonsuchencoding,anditisalsovariablelength,meaningthatacharactercanbetwo w c h a r _ t .
Themorecommonlyusedstringfunctions
Theninemostcommonlyusedfunctionsinthestringlibraryare:
s t r c a t concatenatetwostrings
en.wikibooks.org/wiki/C_Programming/Print_version
94/118
10/24/13
s t r c h r stringscanningoperation s t r c m p comparetwostrings s t r c p y copyastring s t r l e n getstringlength s t r n c a t concatenateonestringwithpartofanother s t r n c m p comparepartsoftwostrings s t r n c p y copypartofastring s t r r c h r stringscanningoperation
The s t r c a t function
c h a r* s t r c a t ( c h a r*r e s t r i c ts 1 ,c o n s tc h a r*r e s t r i c ts 2 ) ;
Somepeoplerecommendusing s t r n c a t ( ) or s t r l c a t ( ) insteadofstrcat,inordertoavoidbufferoverflow. The s t r c a t ( ) functionshallappendacopyofthestringpointedtoby s 2 (includingtheterminatingnullbyte)totheendofthestringpointedtoby s 1 .Theinitialbyteof s 2 overwritesthenullbyteattheendof s 1 .Ifcopyingtakesplacebetweenobjectsthat overlap,thebehaviorisundefined.Thefunctionreturns s 1 . Thisfunctionisusedtoattachonestringtotheendofanotherstring.Itisimperativethatthefirststring(s 1 )havethespaceneededtostorebothstrings. Example:
# i n c l u d e< s t d i o . h > # i n c l u d e< s t r i n g . h > . . . s t a t i cc o n s tc h a r* c o l o r s [ ]={ " R e d " , " O r a n g e " , " Y e l l o w " , " G r e e n " , " B l u e " , " P u r p l e "} ; s t a t i cc o n s tc h a r* w i d t h s [ ]={ " T h i n " , " M e d i u m " , " T h i c k " , " B o l d "} ; . . . c h a rp e n T e x t [ 2 0 ] ; . . . i n tp e n C o l o r=3 ,p e n T h i c k n e s s=2 ; s t r c p y ( p e n T e x t ,c o l o r s [ p e n C o l o r ] ) ; s t r c a t ( p e n T e x t ,w i d t h s [ p e n T h i c k n e s s ] ) ; p r i n t f ( " M yp e ni s% s \ n " ,p e n T e x t ) ;/ /p r i n t s' M yp e ni sG r e e n T h i c k '
The s t r c h r function
c h a r* s t r c h r ( c o n s tc h a r* s ,i n tc ) ;
The s t r c h r ( ) functionshalllocatethefirstoccurrenceof c (convertedtoa c h a r )inthestringpointedtoby s .Theterminatingnullbyteisconsideredtobepartofthestring.Thefunctionreturnsthelocationofthefoundcharacter,oranullpointerifthe characterwasnotfound. Thisfunctionisusedtofindcertaincharactersinstrings. Atonepointinhistory,thisfunctionwasnamed i n d e x .The s t r c h r name,howevercryptic,fitsthegeneralpatternfornaming. Thefollowingisapublicdomainimplementationof s t r c h r :
# i n c l u d e< s t r i n g . h > / *s t r c h r* / c h a r* ( s t r c h r ) ( c o n s tc h a r* s ,i n tc ) { / *S c a nsf o rt h ec h a r a c t e r . W h e nt h i sl o o pi sf i n i s h e d , sw i l le i t h e rp o i n tt ot h ee n do ft h es t r i n go rt h e
en.wikibooks.org/wiki/C_Programming/Print_version
95/118
10/24/13
c h a r a c t e rw ew e r el o o k i n gf o r . * / w h i l e( * s! =' \ 0 '& &* s! =( c h a r ) c ) s + + ; r e t u r n(( * s= =c )?( c h a r* )s:N U L L) ; }
The s t r c m p function
i n ts t r c m p ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ) ;
Arudimentaryformofstringcomparisonisdonewiththestrcmp()function.Ittakestwostringsasargumentsandreturnsavaluelessthanzeroifthefirstislexographicallylessthanthesecond,avaluegreaterthanzeroifthefirstislexographically greaterthanthesecond,orzeroifthetwostringsareequal.Thecomparisonisdonebycomparingthecoded(ascii)valueofthechararacters,characterbycharacter. Thissimpletypeofstringcomparisonisnowadaysgenerallyconsideredunacceptablewhensortinglistsofstrings.Moreadvancedalgorithmsexistthatarecapableofproducinglistsindictionarysortedorder.Theycanalsofixproblemssuchasstrcmp() consideringthestring"Alpha2"greaterthan"Alpha12".(Inthepreviousexample,"Alpha2"comparesgreaterthan"Alpha12"because'2'comesafter'1'inthecharacterset.)Whatwe'resayingis,don'tusethis s t r c m p ( ) aloneforgeneralstringsortinginany commercialorprofessionalcode. The s t r c m p ( ) functionshallcomparethestringpointedtoby s 1 tothestringpointedtoby s 2 .Thesignofanonzeroreturnvalueshallbedeterminedbythesignofthedifferencebetweenthevaluesofthefirstpairofbytes(bothinterpretedastype u n s i g n e d c h a r )thatdifferinthestringsbeingcompared.Uponcompletion, s t r c m p ( ) shallreturnanintegergreaterthan,equalto,orlessthan0,ifthestringpointedtoby s 1 isgreaterthan,equalto,orlessthanthestringpointedtoby s 2 ,respectively. Sincecomparingpointersbythemselvesisnotpracticallyusefulunlessoneiscomparingpointerswithinthesamearray,thisfunctionlexicallycomparesthestringsthattwopointerspointto. Thisfunctionisusefulincomparisons,e.g.
i f( s t r c m p ( s ," w h a t e v e r " )= =0 )/ *d os o m e t h i n g* / ;
The s t r c p y function
c h a r* s t r c p y ( c h a r* r e s t r i c ts 1 ,c o n s tc h a r* r e s t r i c ts 2 ) ;
Somepeoplerecommendalwaysusing s t r n c p y ( ) insteadofstrcpy,toavoidbufferoverflow. The s t r c p y ( ) functionshallcopytheCstringpointedtoby s 2 (includingtheterminatingnullbyte)intothearraypointedtoby s 1 .Ifcopyingtakesplacebetweenobjectsthatoverlap,thebehaviorisundefined.Thefunctionreturns s 1 .Thereisnovalueused toindicateanerror:iftheargumentsto s t r c p y ( ) arecorrect,andthedestinationbufferislargeenough,thefunctionwillneverfail. Example:
# i n c l u d e< s t d i o . h > # i n c l u d e< s t r i n g . h > / *. . .* / s t a t i cc o n s tc h a r* p e n T y p e = " r o u n d " ; / *. . .* / c h a rp e n T e x t [ 2 0 ] ; / *. . .* / s t r c p y ( p e n T e x t ,p e n T y p e ) ;
en.wikibooks.org/wiki/C_Programming/Print_version
96/118
10/24/13
Thefollowingisapublicdomainimplementationof s t r c p y :
# i n c l u d e< s t r i n g . h > / *s t r c p y* / c h a r* ( s t r c p y ) ( c h a r* r e s t r i c ts 1 ,c o n s tc h a r* r e s t r i c ts 2 ) { c h a r* d s t=s 1 ; c o n s tc h a r* s r c=s 2 ; / *D ot h ec o p y i n gi nal o o p . * / w h i l e( ( * d s t + +=* s r c + + )! =' \ 0 ' ) ; / *T h eb o d yo ft h i sl o o pi sl e f te m p t y .* / / *R e t u r nt h ed e s t i n a t i o ns t r i n g . * / r e t u r ns 1 ; }
The s t r l e n function
s i z e _ ts t r l e n ( c o n s tc h a r* s ) ;
The s t r n c a t function
c h a r* s t r n c a t ( c h a r* r e s t r i c ts 1 ,c o n s tc h a r* r e s t r i c ts 2 ,s i z e _ tn ) ;
The s t r n c m p function
i n ts t r n c m p ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ,s i z e _ tn ) ;
The s t r n c m p ( ) functionshallcomparenotmorethan n bytes(bytesthatfollowanullbytearenotcompared)fromthearraypointedtoby s 1 tothearraypointedtoby s 2 .Thesignofanonzeroreturnvalueisdeterminedbythesignofthedifferencebetween thevaluesofthefirstpairofbytes(bothinterpretedastype u n s i g n e dc h a r )thatdifferinthestringsbeingcompared.See s t r c m p foranexplanationofthereturnvalue. Thisfunctionisusefulincomparisons,asthe s t r c m p functionis. Thefollowingisapublicdomainimplementationof s t r n c m p :
en.wikibooks.org/wiki/C_Programming/Print_version
97/118
10/24/13
# i n c l u d e< s t r i n g . h > / *s t r n c m p* / i n t( s t r n c m p ) ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ,s i z e _ tn ) { u n s i g n e dc h a ru c 1 ,u c 2 ; / *N o t h i n gt oc o m p a r e ? R e t u r nz e r o . * / i f( n= =0 ) r e t u r n0 ; / *L o o p ,c o m p a r i n gb y t e s . * / w h i l e( n ->0& &* s 1= =* s 2 ){ / *I fw e ' v er u no u to fb y t e so rh i tan u l l ,r e t u r nz e r o s i n c ew ea l r e a d yk n o w* s 1= =* s 2 . * / i f( n= =0| |* s 1= =' \ 0 ' ) r e t u r n0 ; s 1 + + ; s 2 + + ; } u c 1=( * ( u n s i g n e dc h a r* )s 1 ) ; u c 2=( * ( u n s i g n e dc h a r* )s 2 ) ; r e t u r n( ( u c 1<u c 2 )?1:( u c 1>u c 2 ) ) ; }
The s t r n c p y function
c h a r* s t r n c p y ( c h a r* r e s t r i c ts 1 ,c o n s tc h a r* r e s t r i c ts 2 ,s i z e _ tn ) ;
The s t r n c p y ( ) functionshallcopynotmorethan n bytes(bytesthatfollowanullbytearenotcopied)fromthearraypointedtoby s 2 tothearraypointedtoby s 1 .Ifcopyingtakesplacebetweenobjectsthatoverlap,thebehaviorisundefined.Ifthearray pointedtoby s 2 isastringthatisshorterthan n bytes,nullbytesshallbeappendedtothecopyinthearraypointedtoby s 1 ,until n bytesinallarewritten.Thefunctionshallreturns1noreturnvalueisreservedtoindicateanerror. Itispossiblethatthefunctionwill notreturnanullterminatedstring,whichhappensifthe s 2 stringislongerthan n bytes. Thefollowingisapublicdomainversionof s t r n c p y :
# i n c l u d e< s t r i n g . h > / *s t r n c p y* / c h a r* ( s t r n c p y ) ( c h a r* r e s t r i c ts 1 ,c o n s tc h a r* r e s t r i c ts 2 ,s i z e _ tn ) { c h a r* d s t=s 1 ; c o n s tc h a r* s r c=s 2 ; / *C o p yb y t e s ,o n ea tat i m e . * / w h i l e( n>0 ){ n ; i f( ( * d s t + +=* s r c + + )= =' \ 0 ' ){ / *I fw eg e th e r e ,w ef o u n dan u l lc h a r a c t e ra tt h ee n d o fs 2 ,s ou s em e m s e tt op u tn u l lb y t e sa tt h ee n do f s 1 . * / m e m s e t ( d s t ,' \ 0 ' ,n ) ; b r e a k ; } } r e t u r ns 1 ; }
The s t r r c h r function
c h a r* s t r r c h r ( c o n s tc h a r* s ,i n tc ) ; s t r r c h r issimilarto s t r c h r ,exceptthestringissearchedrighttoleft.
The s t r r c h r ( ) functionshalllocatethelastoccurrenceof c (convertedtoa c h a r )inthestringpointedtoby s .Theterminatingnullbyteisconsideredtobepartofthestring.Itsreturnvalueissimilarto s t r c h r 'sreturnvalue. Atonepointinhistory,thisfunctionwasnamed r i n d e x .The s t r r c h r name,howevercryptic,fitsthegeneralpatternfornaming. Thefollowingisapublicdomainimplementationof s t r r c h r :
# i n c l u d e< s t r i n g . h > / *s t r r c h r* / c h a r* ( s t r r c h r ) ( c o n s tc h a r* s ,i n tc ) { c o n s tc h a r* l a s t=N U L L ; / *I ft h ec h a r a c t e rw e ' r el o o k i n gf o ri st h et e r m i n a t i n gn u l l , w ej u s tn e e dt ol o o kf o rt h a tc h a r a c t e ra st h e r e ' so n l yo n e o ft h e mi nt h es t r i n g . * / i f( c= =' \ 0 ' ) r e t u r ns t r c h r ( s ,c ) ; / *L o o pt h r o u g h ,f i n d i n gt h el a s tm a t c hb e f o r eh i t t i n gN U L L . * / w h i l e( ( s=s t r c h r ( s ,c ) )! =N U L L ){ l a s t=s ; s + + ;
en.wikibooks.org/wiki/C_Programming/Print_version
98/118
10/24/13
} r e t u r n( c h a r* )l a s t ; }
Thelesscommonlyusedstringfunctions
Thelessusedfunctionsare:
m e m c h r Findabyteinmemory m e m c m p Comparebytesinmemory m e m c p y Copybytesinmemory m e m m o v e Copybytesinmemorywithoverlappingareas m e m s e t Setbytesinmemory s t r c o l l Comparebytesaccordingtoalocalespecificcollatingsequence s t r c s p n Getthelengthofacomplementarysubstring s t r e r r o r Geterrormessage s t r p b r k Scanastringforabyte s t r s p n Getthelengthofasubstring s t r s t r Findasubstring s t r t o k Splitastringintotokens s t r x f r m Transformstring
Copyingfunctions
Them e m c p y function
v o i d* m e m c p y ( v o i d*r e s t r i c ts 1 ,c o n s tv o i d*r e s t r i c ts 2 ,s i z e _ tn ) ;
Them e m m o v e function
v o i d* m e m m o v e ( v o i d* s 1 ,c o n s tv o i d* s 2 ,s i z e _ tn ) ;
The m e m m o v e ( ) functionshallcopy n bytesfromtheobjectpointedtoby s 2 intotheobjectpointedtoby s 1 .Copyingtakesplaceasifthe n bytesfromtheobjectpointedtoby s 2 arefirstcopiedintoatemporaryarrayof n bytesthatdoesnotoverlaptheobjects pointedtoby s 1 and s 2 ,andthenthe n bytesfromthetemporaryarrayarecopiedintotheobjectpointedtoby s 1 .Thefunctionreturnsthevalueof s 1 . Theeasywaytoimplementthiswithoutusingatemporaryarrayistocheckforaconditionthatwouldpreventanascendingcopy,andiffound,doadescendingcopy. Thefollowingisapublicdomain,thoughnotcompletelyportable,implementationof m e m m o v e :
# i n c l u d e< s t r i n g . h > / *m e m m o v e* / v o i d* ( m e m m o v e ) ( v o i d* s 1 ,c o n s tv o i d* s 2 ,s i z e _ tn ) { / *n o t e :t h e s ed o n ' th a v et op o i n tt ou n s i g n e dc h a r s* / c h a r* p 1=s 1 ; c o n s tc h a r* p 2=s 2 ; / *t e s tf o ro v e r l a pt h a tp r e v e n t sa na s c e n d i n gc o p y* / i f( p 2<p 1& &p 1<p 2+n ){ / *d oad e s c e n d i n gc o p y* / p 2+ =n ; p 1+ =n ;
en.wikibooks.org/wiki/C_Programming/Print_version
99/118
10/24/13
w h i l e( n -! =0 ) * p 1=* p 2 ; }e l s e w h i l e( n -! =0 ) * p 1 + +=* p 2 + + ; r e t u r ns 1 ; }
Comparisonfunctions
Them e m c m p function
i n tm e m c m p ( c o n s tv o i d* s 1 ,c o n s tv o i d* s 2 ,s i z e _ tn ) ;
The m e m c m p ( ) functionshallcomparethefirst n bytes(eachinterpretedas u n s i g n e dc h a r )oftheobjectpointedtoby s 1 tothefirst n bytesoftheobjectpointedtoby s 2 .Thesignofanonzeroreturnvalueshallbedeterminedbythesignofthedifference betweenthevaluesofthefirstpairofbytes(bothinterpretedastype u n s i g n e dc h a r )thatdifferintheobjectsbeingcompared. Thefollowingisapublicdomainimplementationof m e m c m p :
# i n c l u d e< s t r i n g . h > / *m e m c m p* / i n t( m e m c m p ) ( c o n s tv o i d* s 1 ,c o n s tv o i d* s 2 ,s i z e _ tn ) { c o n s tu n s i g n e dc h a r* u s 1=( c o n s tu n s i g n e dc h a r* )s 1 ; c o n s tu n s i g n e dc h a r* u s 2=( c o n s tu n s i g n e dc h a r* )s 2 ; w h i l e( n -! =0 ){ i f( * u s 1! =* u s 2 ) r e t u r n( * u s 1<* u s 2 )?1:+ 1 ; u s 1 + + ; u s 2 + + ; } r e t u r n0 ; }
TheANSICStandardspecifiestwolocalespecificcomparisonfunctions. The s t r c o l l functioncomparesthestringpointedtoby s 1 tothestringpointedtoby s 2 ,bothinterpretedasappropriatetothe L C _ C O L L A T E categoryofthecurrentlocale.Thereturnvalueissimilarto s t r c m p . The s t r x f r m functiontransformsthestringpointedtoby s 2 andplacestheresultingstringintothearraypointedtoby s 1 .Thetransformationissuchthatifthe s t r c m p functionisappliedtothetwotransformedstrings,itreturnsavaluegreaterthan,equalto, orlessthanzero,correspondingtotheresultofthe s t r c o l l functionappliedtothesametwooriginalstrings.Nomorethan n charactersareplacedintotheresultingarraypointedtoby s 1 ,includingtheterminatingnullcharacter.If n iszero, s 1 ispermitted tobeanullpointer.Ifcopyingtakesplacebetweenobjectsthatoverlap,thebehaviorisundefined.Thefunctionreturnsthelengthofthetransformedstring. Thesefunctionsarerarelyusedandnontrivialtocode,sothereisnocodeforthissection. Searchfunctions
Them e m c h r function
v o i d* m e m c h r ( c o n s tv o i d* s ,i n tc ,s i z e _ tn ) ;
The m e m c h r ( ) functionshalllocatethefirstoccurrenceof c (convertedtoan u n s i g n e dc h a r )intheinitial n bytes(eachinterpretedas u n s i g n e dc h a r )oftheobjectpointedtoby s .If c isnotfound, m e m c h r returnsanullpointer. Thefollowingisapublicdomainimplementationof m e m c h r :
# i n c l u d e< s t r i n g . h > / *m e m c h r* / v o i d* ( m e m c h r ) ( c o n s tv o i d* s ,i n tc ,s i z e _ tn ) { c o n s tu n s i g n e dc h a r* s r c=s ; u n s i g n e dc h a ru c=c ; w h i l e( n -! =0 ){ i f( * s r c= =u c ) r e t u r n( v o i d* )s r c ; s r c + + ; } r e t u r nN U L L ; }
en.wikibooks.org/wiki/C_Programming/Print_version
100/118
10/24/13
Thes t r c s p n ,s t r p b r k ,ands t r s p n functions
s i z e _ ts t r c s p n ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ) ; c h a r* s t r p b r k ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ) ; s i z e _ ts t r s p n ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ) ;
The s t r c s p n functioncomputesthelengthofthemaximuminitialsegmentofthestringpointedtoby s 1 whichconsistsentirelyofcharacters notfromthestringpointedtoby s 2 . The s t r p b r k functionlocatesthefirstoccurrenceinthestringpointedtoby s 1 ofanycharacterfromthestringpointedtoby s 2 ,returningapointertothatcharacteroranullpointerifnotfound. The s t r s p n functioncomputesthelengthofthemaximuminitialsegmentofthestringpointedtoby s 1 whichconsistsentirelyofcharactersfromthestringpointedtoby s 2 . Allofthesefunctionsaresimilarexceptinthetestandthereturnvalue. Thefollowingarepublicdomainimplementationsof s t r c s p n , s t r p b r k ,and s t r s p n :
# i n c l u d e< s t r i n g . h > / *s t r c s p n* / s i z e _ t( s t r c s p n ) ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ) { c o n s tc h a r* s c 1 ; f o r( s c 1=s 1 ;* s c 1! =' \ 0 ' ;s c 1 + + ) i f( s t r c h r ( s 2 ,* s c 1 )! =N U L L ) r e t u r n( s c 1-s 1 ) ; r e t u r ns c 1-s 1 ; / *t e r m i n a t i n gn u l l sm a t c h* / } # i n c l u d e< s t r i n g . h > / *s t r p b r k* / c h a r* ( s t r p b r k ) ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ) { c o n s tc h a r* s c 1 ; f o r( s c 1=s 1 ;* s c 1! =' \ 0 ' ;s c 1 + + ) i f( s t r c h r ( s 2 ,* s c 1 )! =N U L L ) r e t u r n( c h a r* ) s c 1 ; r e t u r nN U L L ; / *t e r m i n a t i n gn u l l sm a t c h* / } # i n c l u d e< s t r i n g . h > / *s t r s p n* / s i z e _ t( s t r s p n ) ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ) { c o n s tc h a r* s c 1 ; f o r( s c 1=s 1 ;* s c 1! =' \ 0 ' ;s c 1 + + ) i f( s t r c h r ( s 2 ,* s c 1 )= =N U L L ) r e t u r n( s c 1-s 1 ) ; r e t u r ns c 1-s 1 ; / *t e r m i n a t i n gn u l l sd o n ' tm a t c h* / }
Thes t r s t r function
c h a r* s t r s t r ( c o n s tc h a r* h a y s t a c k ,c o n s tc h a r* n e e d l e ) ;
Thes t r t o k function
en.wikibooks.org/wiki/C_Programming/Print_version
101/118
10/24/13
c h a r* s t r t o k ( c h a r* r e s t r i c ts 1 ,c o n s tc h a r* r e s t r i c td e l i m i t e r s ) ;
Asequenceofcallsto s t r t o k ( ) breaksthestringpointedtoby s 1 intoasequenceoftokens,eachofwhichisdelimitedbyabytefromthestringpointedtoby d e l i m i t e r s .Thefirstcallinthesequencehas s 1 asitsfirstargument,andisfollowedbycallswitha nullpointerastheirfirstargument.Theseparatorstringpointedtoby d e l i m i t e r s maybedifferentfromcalltocall. Thefirstcallinthesequencesearchesthestringpointedtoby s 1 forthefirstbytethatisnotcontainedinthecurrentseparatorstringpointedtoby d e l i m i t e r s .Ifnosuchbyteisfound,thentherearenotokensinthestringpointedtoby s 1 and s t r t o k ( ) shall returnanullpointer.Ifsuchabyteisfound,itisthestartofthefirsttoken. The s t r t o k ( ) functionthensearchesfromthereforabyte(ormultiple,consecutivebytes)thatiscontainedinthecurrentseparatorstring.Ifnosuchbyteisfound,thecurrenttokenextendstotheendofthestringpointedtoby s 1 ,andsubsequentsearches foratokenshallreturnanullpointer.Ifsuchabyteisfound,itisoverwrittenbyanullbyte,whichterminatesthecurrenttoken.The s t r t o k ( ) functionsavesapointertothefollowingbyte,fromwhichthenextsearchforatokenshallstart. Eachsubsequentcall,withanullpointerasthevalueofthefirstargument,startssearchingfromthesavedpointerandbehavesasdescribedabove. The s t r t o k ( ) functionneednotbereentrant.Afunctionthatisnotrequiredtobereentrantisnotrequiredtobethreadsafe. Becausethe s t r t o k ( ) functionmustsavestatebetweencalls,andyoucouldnothavetwotokenizersgoingatthesametime,theSingleUnixStandarddefinedasimilarfunction, s t r t o k _ r ( ) ,thatdoesnotneedtosavestate.Itsprototypeisthis:
c h a r* s t r t o k _ r ( c h a r* s ,c o n s tc h a r* d e l i m i t e r s ,c h a r* * l a s t s ) ;
The s t r t o k _ r ( ) functionconsidersthenullterminatedstring s asasequenceofzeroormoretexttokensseparatedbyspansofoneormorecharactersfromtheseparatorstring d e l i m i t e r s .Theargumentlastspointstoauserprovidedpointerwhichpointsto storedinformationnecessaryfor s t r t o k _ r ( ) tocontinuescanningthesamestring. Inthefirstcallto s t r t o k _ r ( ) , s pointstoanullterminatedstring, d e l i m i t e r s toanullterminatedstringofseparatorcharacters,andthevaluepointedtoby l a s t s isignored.The s t r t o k _ r ( ) functionshallreturnapointertothefirstcharacterofthefirsttoken, writeanullcharacterinto s immediatelyfollowingthereturnedtoken,andupdatethepointertowhich l a s t s points. Insubsequentcalls, s isanullpointerand l a s t s shallbeunchangedfromthepreviouscallsothatsubsequentcallsshallmovethroughthestring s ,returningsuccessivetokensuntilnotokensremain.Theseparatorstring d e l i m i t e r s maybedifferentfrom calltocall.Whennotokenremainsin s ,aNULLpointershallbereturned. Thefollowingpublicdomaincodefor s t r t o k and s t r t o k _ r codestheformerasaspecialcaseofthelatter:
# i n c l u d e< s t r i n g . h > / *s t r t o k _ r* / c h a r* ( s t r t o k _ r ) ( c h a r* s ,c o n s tc h a r* d e l i m i t e r s ,c h a r* * l a s t s ) { c h a r* s b e g i n ,* s e n d ; s b e g i n=s?s:* l a s t s ; s b e g i n+ =s t r s p n ( s b e g i n ,d e l i m i t e r s ) ; i f( * s b e g i n= =' \ 0 ' ){ * l a s t s=" " ; r e t u r nN U L L ; } s e n d=s b e g i n+s t r c s p n ( s b e g i n ,d e l i m i t e r s ) ; i f( * s e n d! =' \ 0 ' ) * s e n d + +=' \ 0 ' ; * l a s t s=s e n d ; r e t u r ns b e g i n ; } / *s t r t o k* / c h a r* ( s t r t o k ) ( c h a r* r e s t r i c ts 1 ,c o n s tc h a r* r e s t r i c td e l i m i t e r s ) { s t a t i cc h a r* s s a v e=" " ; r e t u r ns t r t o k _ r ( s 1 ,d e l i m i t e r s ,& s s a v e ) ; }
Miscellaneousfunctions Thesefunctionsdonotfitintooneoftheabovecategories.
Them e m s e t function
v o i d* m e m s e t ( v o i d* s ,i n tc ,s i z e _ tn ) ;
en.wikibooks.org/wiki/C_Programming/Print_version
102/118
10/24/13
Thes t r e r r o r function
c h a r* s t r e r r o r ( i n te r r o r c o d e ) ;
Thisfunctionstoresthemessagein b u f ,whichhasalengthofsize b u f l e n .
Examples
Todeterminethenumberofcharactersinastring,the s t r l e n ( ) functionisused:
# i n c l u d e< s t d i o . h > # i n c l u d e< s t r i n g . h > . . . i n tl e n g t h ,l e n g t h 2 ; c h a r* t u r k e y ; s t a t i cc h a r* f l o w e r =" b e g o n i a " ; s t a t i cc h a r* g e m s t o n e = " r u b y" ; l e n g t h=s t r l e n ( f l o w e r ) ; p r i n t f ( " L e n g t h=% d \ n " ,l e n g t h ) ;/ /p r i n t s' L e n g t h=7 ' l e n g t h 2=s t r l e n ( g e m s t o n e ) ; t u r k e y=m a l l o c (l e n g t h+l e n g t h 2+1 ) ; i f( t u r k e y ){ s t r c p y (t u r k e y ,g e m s t o n e ) ; s t r c a t (t u r k e y ,f l o w e r ) ; p r i n t f (" % s \ n " ,t u r k e y ) ;/ /p r i n t s' r u b yb e g o n i a ' f r e e (t u r k e y) ; }
Notethattheamountofmemoryallocatedfor'turkey'isoneplusthesumofthelengthsofthestringstobeconcatenated.Thisisfortheterminatingnullcharacter,whichisnotcountedinthelengthsofthestrings.
Exercises
1. Thestringfunctionsusealotofloopingconstructs.Istheresomewaytoportablyunraveltheloops? 2. Whatfunctionsarepossiblymissingfromthelibraryasitstandsnow?
Furtherreading
ALittleCPrimer/CStringFunctionLibrary C++Programming/Code/IO/Streams/string Becausesomanyfunctionsinthestandard s t r i n g . h libraryarevulnerabletobufferoverflowerrors,somepeople(http://www.and.org/vstr/security)recommendavoidingthe s t r i n g . h libraryand"Cstylestrings"andinsteadusingadynamicstringAPI, suchastheoneslistedintheStringlibrarycomparison(http://www.and.org/vstr/comparison). There'satinypublicdomainconcat()function,whichwillallocatememoryandsafelyconcatenateanynumberofstringsinportableC/C++code(http://openwall.info/wiki/people/solar/software/publicdomainsourcecode/concat)
Complextypes
InthesectionCtypeswelookedatsomebasictypes.However CcomplextypesallowusgreaterflexibilityinmanagingdatainourCprogram.
Datastructures
Adatastructure("struct")containsmultiplepiecesofdata.Eachpieceofdata(calleda"member")canbeaccessedbythenameofthevariable,followedbya'.',thenthenameofthemember.(Anotherwaytoaccessamemberisusingthemember operator'>').Themembervariablesofastructcanbeofanydatatypeandcanevenbeanarrayorapointer.
Pointers
Pointersarevariablesthatdon'tholdtheactualdata.Insteadtheypointtothememorylocationofsomeothervariable.Forexample,
i n t* p o i n t e r=& v a r i a b l e ;
en.wikibooks.org/wiki/C_Programming/Print_version
103/118
10/24/13
Thistellsusthatthepointerisn'tcurrentlypointingtoanyreallocation. Additionally,todereference(accessthethingbeingpointedat)thepointer,usetheform:
v a l u e=* p o i n t e r ;
Structs
Adatastructurecontainsmultiplepiecesofdata.Onedefinesadatastructureusingthe s t r u c t keyword.Forexample,
s t r u c tm y s t r u c t { i n ti n t _ m e m b e r ; d o u b l ed o u b l e _ m e m b e r ; c h a rs t r i n g _ m e m b e r [ 2 5 ] ; }v a r i a b l e ;
v a r i a b l e isaninstanceof m y s t r u c t .Youcanomititfromtheendofthe s t r u c t declarationanddeclareitlaterusing:
s t r u c tm y s t r u c tv a r i a b l e ;
Unions
Thedefinitionofaunionissimilartothatofastruct.Thedifferencebetweenthetwoisthatinastruct,themembersoccupydifferentareasofmemory,butinaunion,themembersoccupythesameareaofmemory.Thus,inthefollowingtype,for example:
u n i o n{ i n ti ; d o u b l ed ; }u ;
en.wikibooks.org/wiki/C_Programming/Print_version
104/118
10/24/13
Thesizeofaunionisthesizeofitslargestmember.
Typemodifiers
For"register","volatile","auto"and"extern",seeCProgramming/Variables#Other_Modifiers.
NetworkinginUNIX
NetworkprogrammingunderUNIXisrelativelysimpleinC. ThisguideassumesyoualreadyhaveagoodgeneralideaaboutC,UNIXandnetworks.
Asimpleclient
Tostartwith,we'lllookatoneofthesimplestthingsyoucando:initializeastreamconnectionandreceiveamessagefromaremoteserver.
# i n c l u d e< s t d i o . h > # i n c l u d e< s t d l i b . h > # i n c l u d e< s t r i n g . h > # i n c l u d e< u n i s t d . h > # i n c l u d e< a r p a / i n e t . h > # i n c l u d e< s y s / t y p e s . h > # i n c l u d e< n e t i n e t / i n . h > # i n c l u d e< s y s / s o c k e t . h > # d e f i n eM A X R C V L E N5 0 0 # d e f i n eP O R T N U M2 3 4 3 i n tm a i n ( i n ta r g c ,c h a r* a r g v [ ] ) { c h a rb u f f e r [ M A X R C V L E N+1 ] ;/ *+ 1s ow ec a na d dn u l lt e r m i n a t o r* / i n tl e n ,m y s o c k e t ; s t r u c ts o c k a d d r _ i nd e s t ; m y s o c k e t=s o c k e t ( A F _ I N E T ,S O C K _ S T R E A M ,0 ) ; m e m s e t ( & d e s t ,0 ,s i z e o f ( d e s t ) ) ; / *z e r ot h es t r u c t* / d e s t . s i n _ f a m i l y=A F _ I N E T ; d e s t . s i n _ a d d r . s _ a d d r=i n e t _ a d d r ( " 1 2 7 . 0 . 0 . 1 " ) ;/ *s e td e s t i n a t i o nI Pn u m b e r* / d e s t . s i n _ p o r t=h t o n s ( P O R T N U M ) ; / *s e td e s t i n a t i o np o r tn u m b e r* / c o n n e c t ( m y s o c k e t ,( s t r u c ts o c k a d d r* ) & d e s t ,s i z e o f ( s t r u c ts o c k a d d r ) ) ; l e n=r e c v ( m y s o c k e t ,b u f f e r ,M A X R C V L E N ,0 ) ; / *W eh a v et on u l lt e r m i n a t et h er e c e i v e dd a t ao u r s e l v e s* / b u f f e r [ l e n ]=' \ 0 ' ; p r i n t f ( " R e c e i v e d% s( % db y t e s ) . \ n " ,b u f f e r ,l e n ) ; c l o s e ( m y s o c k e t ) ; r e t u r nE X I T _ S U C C E S S ; }
The s o c k e t ( ) functiontellsourOSthatwewantafiledescriptorforasocketwhichwecanuseforanetworkstreamconnectionwhattheparametersmeanismostlyirrelevantfornow.
m e m s e t ( & d e s t ,0 ,s i z e o f ( d e s t ) ) ; / *z e r ot h es t r u c t* / d e s t . s i n _ f a m i l y=A F _ I N E T ; d e s t . s i n _ a d d r . s _ a d d r=i n e t _ a d d r ( " 1 2 7 . 0 . 0 . 1 " ) ;/ *s e td e s t i n a t i o nI Pn u m b e r* / d e s t . s i n _ p o r t=h t o n s ( P O R T N U M ) ; / *s e td e s t i n a t i o np o r tn u m b e r* /
en.wikibooks.org/wiki/C_Programming/Print_version
105/118
10/24/13
ThethirdlineiswherewesettheIPofthemachineweneedtoconnectto.Thevariable d e s t . s i n _ a d d r . s _ a d d r isjustanintegerstoredinBigEndianformat,butwedon'thavetoknowthatasthe i n e t _ a d d r ( ) functionwilldotheconversionfromstringintoBig Endianintegerforus. Thefourthlinesetsthedestinationportnumber.The h t o n s ( ) functionconvertstheportnumberintoaBigEndianshortinteger.IfyourprogramisgoingtoberunsolelyonmachineswhichuseBigEndiannumbersasdefaultthen d e s t . s i n _ p o r t=2 1 would workjustaswell.However,forportabilityreasons h t o n s ( ) shouldalwaysbeused. Nowthatallofthepreliminaryworkisdone,wecanactuallymaketheconnectionanduseit:
c o n n e c t ( m y s o c k e t ,( s t r u c ts o c k a d d r* ) & d e s t ,s i z e o f ( s t r u c ts o c k a d d r ) ) ;
ThistellsourOStousethesocket m y s o c k e t tocreateaconnectiontothemachinespecifiedin d e s t .
l e n=r e c v ( m y s o c k e t ,b u f f e r ,M A X R C V L E N ,0 ) ;
Nowthisreceivesupto M A X R C V L E N bytesofdatafromtheconnectionandstorestheminthebufferstring.Thenumberofcharactersreceivedisreturnedby r e c v ( ) .Itisimportanttonotethatthedatareceivedwillnotautomaticallybenullterminatedwhen storedinthebuffer,soweneedtodoitourselveswith b u f f e r [ i n p u t l e n ]=' \ 0 ' . Andthat'saboutit! Thenextstepafterlearninghowtoreceivedataislearninghowtosendit.Ifyou'veunderstoodtheprevioussectionthenthisisquiteeasy.Allyouhavetodoisusethe s e n d ( ) function,whichusesthesameparametersas r e c v ( ) .Ifinourpreviousexample b u f f e r hadthetextwewantedtosendanditslengthwasstoredin l e n wewouldwrite s e n d ( m y s o c k e t ,b u f f e r ,l e n ,0 ) . s e n d ( ) returnsthenumberofbytesthatweresent.Itisimportanttorememberthat s e n d ( ) ,forvariousreasons,maynotbeabletosendallof thebytes,soitisimportanttocheckthatitsreturnvalueisequaltothenumberofbytesyoutriedtosend.Inmostcasesthiscanberesolvedbyresendingtheunsentdata.
Asimpleserver
# i n c l u d e< s t d i o . h > # i n c l u d e< s t d l i b . h > # i n c l u d e< s t r i n g . h > # i n c l u d e< u n i s t d . h > # i n c l u d e< a r p a / i n e t . h > # i n c l u d e< s y s / t y p e s . h > # i n c l u d e< n e t i n e t / i n . h > # i n c l u d e< s y s / s o c k e t . h > # d e f i n eP O R T N U M2 3 4 3 i n tm a i n ( i n ta r g c ,c h a r* a r g v [ ] ) { c h a rm s g [ ]=" H e l l oW o r l d! \ n " ; s t r u c ts o c k a d d r _ i nd e s t ;/ *s o c k e ti n f oa b o u tt h em a c h i n ec o n n e c t i n gt ou s* / s t r u c ts o c k a d d r _ i ns e r v ;/ *s o c k e ti n f oa b o u to u rs e r v e r* / i n tm y s o c k e t ; / *s o c k e tu s e dt ol i s t e nf o ri n c o m i n gc o n n e c t i o n s* / s o c k l e n _ ts o c k s i z e=s i z e o f ( s t r u c ts o c k a d d r _ i n ) ; m e m s e t ( & s e r v ,0 ,s i z e o f ( s e r v ) ) ; / *z e r ot h es t r u c tb e f o r ef i l l i n gt h ef i e l d s* / s e r v . s i n _ f a m i l y=A F _ I N E T ; / *s e tt h et y p eo fc o n n e c t i o nt oT C P / I P* / s e r v . s i n _ a d d r . s _ a d d r=h t o n l ( I N A D D R _ A N Y ) ;/ *s e to u ra d d r e s st oa n yi n t e r f a c e* / s e r v . s i n _ p o r t=h t o n s ( P O R T N U M ) ; / *s e tt h es e r v e rp o r tn u m b e r* / m y s o c k e t=s o c k e t ( A F _ I N E T ,S O C K _ S T R E A M ,0 ) ; / *b i n ds e r vi n f o r m a t i o nt om y s o c k e t* / b i n d ( m y s o c k e t ,( s t r u c ts o c k a d d r* ) & s e r v ,s i z e o f ( s t r u c ts o c k a d d r ) ) ; / *s t a r tl i s t e n i n g ,a l l o w i n gaq u e u eo fu pt o1p e n d i n gc o n n e c t i o n* / l i s t e n ( m y s o c k e t ,1 ) ; i n tc o n s o c k e t=a c c e p t ( m y s o c k e t ,( s t r u c ts o c k a d d r* ) & d e s t ,& s o c k s i z e ) ; w h i l e ( c o n s o c k e t ) { p r i n t f ( " I n c o m i n gc o n n e c t i o nf r o m% s-s e n d i n gw e l c o m e \ n " ,i n e t _ n t o a ( d e s t . s i n _ a d d r ) ) ; s e n d ( c o n s o c k e t ,m s g ,s t r l e n ( m s g ) ,0 ) ; c o n s o c k e t=a c c e p t ( m y s o c k e t ,( s t r u c ts o c k a d d r* ) & d e s t ,& s o c k s i z e ) ; } c l o s e ( c o n s o c k e t ) ; c l o s e ( m y s o c k e t ) ; r e t u r nE X I T _ S U C C E S S ; }
Superficially,thisisverysimilartotheclient.Thefirstimportantdifferenceisthatratherthancreatinga s o c k a d d r _ i n withinformationaboutthemachinewe'reconnectingto,wecreateitwithinformationabouttheserver,andthenwe b i n d ( ) ittothesocket. Thisallowsthemachinetoknowthedatareceivedontheportspecifiedinthe s o c k a d d r _ i n shouldbehandledbyourspecifiedsocket. The l i s t e n ( ) functionthentellsourprogramtostartlisteningusingthegivensocket.Thesecondparameterof l i s t e n ( ) allowsustospecifythemaximumnumberofconnectionsthatcanbequeued.Eachtimeaconnectionismadetotheserveritisadded tothequeue.Wetakeconnectionsfromthequeueusingthe a c c e p t ( ) function.Ifthereisnoconnectionwaitingonthequeuetheprogramwaitsuntilaconnectionisreceived.The a c c e p t ( ) functionreturnsanothersocket.Thissocketisessentiallya "session"socket,andcanbeusedsolelyforcommunicatingwithconnectionwetookoffthequeue.Theoriginalsocket(m y s o c k e t )continuestolistenonthespecifiedportforfurtherconnections.
en.wikibooks.org/wiki/C_Programming/Print_version
106/118
10/24/13
Usefulnetworkfunctions
i n tg e t h o s t n a m e ( c h a r* h o s t n a m e ,s i z e _ ts i z e ) ;
Theparametersareapointertoanarrayofcharsandthesizeofthatarray.Ifpossible,itfindsthehostnameandstoresitinthearray.Onfailureitreturns1.
s t r u c th o s t e n t* g e t h o s t b y n a m e ( c o n s tc h a r* n a m e ) ;
FAQs
Whataboutstatelessconnections?
Ifyoudon'twanttoexploitthepropertiesofTCPinyourprogramandwouldratherjustuseaUDPconnection,thenyoucanjustreplace S O C K _ S T R E A M with S O C K _ D G R A M inyourcallto s o c k e t ( ) andusetheresultinthesameway.Itisimportanttorememberthat UDPdoesnotguaranteedeliveryofpacketsandorderofdelivery,socheckingisimportant. IfyouwanttoexploitthepropertiesofUDP,thenyoucanuse s e n d t o ( ) and r e c v f r o m ( ) ,whichoperatelike s e n d ( ) and r e c v ( ) exceptyouneedtoprovideextraparametersspecifyingwhoyouarecommunicatingwith.
HowdoIcheckforerrors?
Thefunctions s o c k e t ( ) , r e c v ( ) and c o n n e c t ( ) allreturn1onfailureanduseerrnoforfurtherdetails.
Commonpractices
Withitsextensiveuse,anumberofcommonpracticesandconventionshaveevolvedtohelpavoiderrorsinCprograms.Thesearesimultaneouslyademonstrationoftheapplicationofgoodsoftwareengineeringprinciplestoalanguageandanindication ofthelimitationsofC.Althoughfewareuseduniversally,andsomearecontroversial,eachoftheseenjoyswideuse.
Dynamicmultidimensionalarrays
Althoughonedimensionalarraysareeasytocreatedynamicallyusingmalloc,andfixedsizemultidimensionalarraysareeasytocreateusingthebuiltinlanguagefeature,dynamicmultidimensionalarraysaretrickier.Thereareanumberofdifferentways tocreatethem,eachwithdifferenttradeoffs.Thetwomostpopularwaystocreatethemare: Theycanbeallocatedasasingleblockofmemory,justlikestaticmultidimensionalarrays.Thisrequiresthatthearraybe rectangular(i.e.subarraysoflowerdimensionsarestaticandhavethesamesize).Thedisadvantageisthatthesyntaxof declarationthepointerisalittletrickyforprogrammersatfirst.Forexample,ifonewantedtocreateanarrayofintsof3columnsand r o w s rows,onewoulddo
i n t( * m u l t i _ a r r a y ) [ 3 ]=m a l l o c ( r o w s*s i z e o f ( i n t [ 3 ] ) ) ;
(Notethathere m u l t i _ a r r a y isapointertoanarrayof3ints.) Becauseofarraypointerinterchangeability,youcanindexthisjustlikestaticmultidimensionalarrays,i.e. m u l t i _ a r r a y [ 5 ] [ 2 ] istheelementatthe6throwand3rdcolumn. Theycanbeallocatedbyfirstallocatinganarrayofpointers,andthenallocatingsubarraysandstoringtheiraddressesinthearrayofpointers(thisapproachisalsoknownasanIliffevector).Thesyntaxforaccessingelementsisthesameasfor multidimensionalarraysdescribedabove(eventhoughtheyarestoredverydifferently).Thisapproachhastheadvantageoftheabilitytomakeraggedarrays(i.e.withsubarraysofdifferentsizes).However,italsousesmorespaceandrequires morelevelsofindirectiontoindexinto,andcanhaveworsecacheperformance.Italsorequiresmanydynamicallocations,eachofwhichcanbeexpensive. Formoreinformation,seethecomp.lang.cFAQ,question6.16(http://www.eskimo.com/~scs/Cfaq/q6.16.html). Insomecases,theuseofmultidimensionalarrayscanbestbeaddressedasanarrayofstructures.Beforeuserdefineddatastructureswereavailable,acommontechniquewastodefineamultidimensionalarray,whereeachcolumncontaineddifferent informationabouttherow.Thisapproachisalsofrequentlyusedbybeginnerprogrammers.Forexample,columnsofatwodimensionalcharacterarraymightcontainlastname,firstname,address,etc. Incaseslikethis,itisbettertodefineastructurethatcontainstheinformationthatwasstoredinthecolumns,andthencreateanarrayofpointerstothatstructure.Thisisespeciallytruewhenthenumberofdatapointsforagivenrecordmightvary,such asthetracksonanalbum.Inthesecases,itisbettertocreateastructureforthealbumthatcontainsinformationaboutthealbum,alongwithadynamicarrayforthelistofsongsonthealbum.Thenanarrayofpointerstothealbumstructurecanbe usedtostorethecollection. Anotherusefulwaytocreateadynamicmultidimensionalarrayistoflattenthearrayandindexmanually.Forexample,a2dimensionalarraywithsizesxandyhasx*yelements,thereforecanbecreatedby
i n td y n a m i c _ m u l t i _ a r r a y [ x * y ] ;
en.wikibooks.org/wiki/C_Programming/Print_version
107/118
10/24/13
Theindexisslightlytrickierthanbefore,butcanstillbeobtainedbyy*i+j.Youthenaccessthearraywith
s t a t i c _ m u l t i _ a r r a y [ i ] [ j ] ; d y n a m i c _ m u l t i _ a r r a y [ y * i + j ] ;
Somemoreexampleswithhigherdimensions:
i n td i m 1 [ w ] ; i n td i m 2 [ w * x ] ; i n td i m 3 [ w * x * y ] ; i n td i m 4 [ w * x * y * z ] ; d i m 1 [ i ] d i m 2 [ w * j + i ] ; d i m 3 [ w * ( x * i + j ) + k ]/ /i n d e xi sk+w * j+w * x * i d i m 4 [ w * ( x * ( y * i + j ) + k ) + l ]/ /i n d e xi sw * x * y * i+w * x * j+w * k+l
Constructorsanddestructors
Inmostobjectorientedlanguages,objectscannotbecreateddirectlybyaclientthatwishestousethem.Instead,theclientmustasktheclasstobuildaninstanceoftheobjectusingaspecialroutinecalledaconstructor.Constructorsareimportant becausetheyallowanobjecttoenforceinvariantsaboutitsinternalstatethroughoutitslifetime.Destructors,calledattheendofanobject'slifetime,areimportantinsystemswhereanobjectholdsexclusiveaccesstosomeresource,anditisdesirableto ensurethatitreleasestheseresourcesforusebyotherobjects. SinceCisnotanobjectorientedlanguage,ithasnobuiltinsupportforconstructorsordestructors.Itisnotuncommonforclientstoexplicitlyallocateandinitializerecordsandotherobjects.However,thisleadstoapotentialforerrors,sinceoperationson theobjectmayfailorbehaveunpredictablyiftheobjectisnotproperlyinitialized.Abetterapproachistohaveafunctionthatcreatesaninstanceoftheobject,possiblytakinginitializationparameters,asinthisexample:
s t r u c ts t r i n g{ s i z e _ ts i z e ; c h a r* d a t a ; } ;
Similarly,ifitislefttotheclienttodestroyobjectscorrectly,theymayfailtodoso,causingresourceleaks.Itisbettertohaveanexplicitdestructorwhichisalwaysused,suchasthisone:
v o i df r e e _ s t r i n g ( s t r u c ts t r i n g* s ){ a s s e r t( s! =N U L L ) ; f r e e ( s > d a t a ) ; / *f r e em e m o r yh e l db yt h es t r u c t u r e* / f r e e ( s ) ; / *f r e et h es t r u c t u r ei t s e l f* / }
Nullingfreedpointers
Asdiscussedearlier,after f r e e ( ) hasbeencalledonapointer,itbecomesadanglingpointer.Worsestill,mostmodernplatformscannotdetectwhensuchapointerisusedbeforebeingreassigned. Onesimplesolutiontothisistoensurethatanypointerissettoanullpointerimmediatelyafterbeingfreed: [18]
en.wikibooks.org/wiki/C_Programming/Print_version
108/118
10/24/13
f r e e ( p ) ; p=N U L L ;
Unlikedanglingpointers,ahardwareexceptionwillariseonmanymodernarchitectureswhenanullpointerisdereferenced.Also,programscanincludeerrorchecksforthenullvalue,butnotforadanglingpointervalue.Toensureitisdoneatall locations,amacrocanbeused:
# d e f i n eF R E E ( p ) d o{f r e e ( p ) ;( p )=N U L L ;}w h i l e ( 0 )
Unfortunately,thisidiomwillnotdoanythingtoanyotherpointersthatmaybepointingtothefreedmemory.Forthisreason,someCexpertsregardthisidiomasdangerousduetocreatingafalsesenseofsecurity.
Macroconventions
BecausepreprocessormacrosinCworkusingsimpletokenreplacement,theyarepronetoanumberofconfusingerrors,someofwhichcanbeavoidedbyfollowingasimplesetofconventions: 1. Placingparenthesesaroundmacroargumentswhereverpossible.Thisensuresthat,iftheyareexpressions,theorderofoperationsdoesnotaffectthebehavioroftheexpression.Forexample: Wrong: # d e f i n es q u a r e ( x )x * x Better: # d e f i n es q u a r e ( x )( x ) * ( x ) 2. Placingparenthesesaroundtheentireexpressionifitisasingleexpression.Again,thisavoidschangesinmeaningduetotheorderofoperations. Wrong: # d e f i n es q u a r e ( x )( x ) * ( x ) Better: # d e f i n es q u a r e ( x )( ( x ) * ( x ) ) Dangerous,rememberitreplacesthetextinverbatim.Supposeyourcodeis s q u a r e( x + + ) ,afterthemacroinvocationwillxbeincrementedby2 3. Ifamacroproducesmultiplestatements,ordeclaresvariables,itcanbewrappedina do{...} while(0)loop,withnoterminatingsemicolon.Thisallowsthemacrotobeusedlikeasinglestatementinanylocation,suchasthebodyofanif statement,whilestillallowingasemicolontobeplacedafterthemacroinvocationwithoutcreatinganullstatement.Caremustbetakenthatanynewvariablesdonotpotentiallymaskportionsofthemacro'sarguments. Wrong: # d e f i n eF R E E ( p )f r e e ( p ) ;p=N U L L ; Better: # d e f i n eF R E E ( p )d o{f r e e ( p ) ;p=N U L L ;}w h i l e ( 0 ) 4. Avoidingusingamacroargumenttwiceormoreinsideamacro,ifpossiblethiscausesproblemswithmacroargumentsthatcontainsideeffects,suchasassignments. 5. Ifamacromaybereplacedbyafunctioninthefuture,consideringnamingitlikeafunction.
Furtherreading
1. Severalprogrammersrecommend"usespacesforindentation.Donotusetabsinyourcode.Youshouldsetyoureditortoemitspaceswhenyouhitthetabkey."[1](http://googlestyleguide.googlecode.com/svn/trunk/cppguide.xml)[2] (http://www.jwz.org/doc/tabsvsspaces.html)Otherprogrammersdisagree.[3](http://diagrammesmodernes.blogspot.com/2006/04/tabversusspaces.html)[4](http://www.derkarl.org/why_to_tabs.html)Regardlessofwhetheryoupreferspacesor tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5](http://www.oualline.com/vimcook.html#drawing) 3. [http://lxr.linux.no/#linux+v2.6.31/Documentation/CodingStyleLinuxKernelcodingstandard 4. "CodingConventionsforC++andJava"(http://www.macadamian.com/index.php?option=com_content&task=view&id=34&Itemid=37)"alltheblockcommentsillustratedinthisdocumenthavenoprettystarsontherightsideoftheblockcomment. Thisdeliberatechoicewasmadebecausealigningthoseprettystarsisalargewasteoftimeanddiscouragesthemaintenanceofinlinecomments.", 5. wiki:BigBlocksOfAsterisks,"Codecraft"(http://books.google.com/books? id=i4zCzpkrt4sC&pg=PA82&lpg=PA82&dq=programming+comment+block+waste+time+lining+up&source=bl&ots=TUpTMIHBnh&sig=NeZm23WPmvnw2aKMnIRUeQoHmJg&hl=en&ei=pri3SevGIYGyNMn9jd4K&sa=X&oi=book_result&resnum=8&ct=result) byPeteGoodliffepage82,Falvotech"CProgrammingStyleGuide"(http://www.falvotech.com/content/publications/conventions/c/),FedoraDirectoryServerCodingStyle(http://directory.fedoraproject.org/wiki/Coding_Style) ThereareahugenumberofCstyleguidelines. "CandC++StyleGuides"(http://www.chrislott.org/resources/cstyle/)byChrisLottlistsmanypopularCstyleguides. TheMotorIndustrySoftwareReliabilityAssociation(MISRA)publishes"MISRAC:GuidelinesfortheuseoftheClanguageincriticalsystems".(Wikipedia:MISRAC[7](http://www.misrac.com/)).
Candbeyond Languageextensions
MostCcompilershaveoneormore"extensions"tothestandardClanguage,todothingsthatareinconvenienttodoinstandard,portableC.
en.wikibooks.org/wiki/C_Programming/Print_version
109/118
10/24/13
Someexamplesoflanguageextensions: inlineassemblylanguage interruptserviceroutines
Externallinks
GNUC:ExtensionstotheCLanguage(http://gcc.gnu.org/onlinedocs/gcc4.0.2/gcc/CExtensions.html#CExtensions) C/C++interpreterChextensionstotheClanguageforscripting(http://www.softintegration.com/support/faq/general.html#4) SDCC:StorageClassLanguageExtensions(http://sdcc.sourceforge.net/doc/sdccman.html/node56.html) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. GCC:"Optimizecommonrotateconstructs"(http://gcc.gnu.org/ml/gccpatches/200711/msg01112.html) "CleanupsinROTL/ROTRDAGcombinercode"(http://www.mailarchive.com/[email protected]/msg17216.html)mentionsthatthiscodesupportsthe"rotate"instructionintheCellSPU "replaceprivatecopyofbitrotationroutines"(http://kerneltrap.org/mailarchive/linuxkernel/2008/4/15/1440064)recommendsincludeing"bitops.h"andusingitsrol32andror32ratherthancopyandpasteintoanewprogram. CFAQ(http://www.cfaq.com/bool/bool2.html) UnderstandingC++/CPreprocessor DavidHart,JonReid."9CodeSmellsofPreprocessorUse"(http://qualitycoding.org/preprocessor/).2012. HPCCompilerReferenceManual(http://docs.hp.com/en/B390190003/ch07s04.html) C++reference:Predefinedpreprocessorvariables(http://www.cppreference.com/wiki/preprocessor/preprocessor_vars) "CompileTimeAssertionsinC"(http://www.jaggersoft.com/pubs/CVu11_3.html)byJonJagger1999 Wikipedia:C++0x#Staticassertions Wirzenius,Lars.CPreprocessorTrickForImplementingSimilarDataTypes(http://liw.iki.fi/liw/texts/cpptrick.html)RetrievedJanuary9,2011. Meyers,Randy(May2001)."TheNewC:XMacros". Dr.Dobb'sJournal.http://www.ddj.com/cpp/184401387.Retrieved1May2008. Beal,Stephan(August2004). Supermacros.http://wanderinghorse.net/computing/papers/#supermacros.Retrieved27October2008. KeithSchwarz."AdvancedPreprocessorTechniques"(http://www.keithschwarz.com/cs106l/spring2009/handouts/080_Preprocessor_2.pdf).2009.Includes"PracticalApplicationsofthePreprocessorII:TheXMacroTrick". Wirzenius,Lars.CPreprocessorTrickForImplementingSimilarDataTypes(http://liw.iki.fi/liw/texts/cpptrick.html)RetrievedJanuary9,2011. C996.2.5/15 "Bug478901...libpng1.2.34andearliermightfreeundefinedpointers"(https://bugzilla.mozilla.org/show_bug.cgi?id=478901) comp.lang.cFAQlist:"Whyisn'tapointernullaftercallingfree?"(http://cfaq.com/malloc/ptrafterfree.html)mentionsthat"itisoftenusefultoset[pointervariables]toNULLimmediatelyafterfreeingthem". comp.lang.cFAQlist:Question2.6(http://cfaq.com/struct/structhack.html):"C99introducestheconceptofaflexiblearraymember,whichallowsthesizeofanarraytobeomittedifitisthelastmemberinastructure,thusprovidingawell definedsolution."
Mixinglanguages
Assembler
SeeEmbeddedSystems/MixedCandAssemblyProgramming
Cg
Makethemainprogram(forCPU)inC,whichloadsandruntheCgprogram(forGPU). [1][2][3]
HeaderFiles
AddtoCprogram: [4]
# i n c l u d e< C g / c g . h >/ *T oi n c l u d et h ec o r eC gr u n t i m eA P Ii n t oy o u r p r o g r a m* / # i n c l u d e< C g / c g G L . h > / *t oi n c l u d et h eO p e n G L s p e c i f i cC gr u n t i m eA P I* /
Java
UsingtheJavanativeinterface(JNI),JavaapplicationscancallClibraries. Seealso
en.wikibooks.org/wiki/C_Programming/Print_version
110/118
10/24/13
Java_Programming/Keywords/native
Perl
TomixPerlandC,wecanuseXS.XSisaninterfacedescriptionfileformatusedtocreateanextensioninterfacebetweenPerlandCcode(oraClibrary)whichonewishestousewithPerl. Thebasicprocedureisverysimple.Wecancreatethenecessarysubdirectorystructurebyrunning"h2xs"application(e.g."h2xsAnModulename").ThiswillcreateamongothersaMakefile.PL,a.pmPerlmoduleanda.xsXSUBfileinthe subdirectorytree.Wecaneditthe.xsfilebyaddingourcodetothat,let'ssay:
v o i d h e l l o ( ) C O D E : p r i n t f ( " H e l l o ,w o r l d ! \ n " ) ;
andwecansuccessfullyuseournewcommandatPerlside,afterrunninga"perlMakefile.PL"and"make". Furtherdetailscanbefoundontheperlxstut(http://perldoc.perl.org/perlxstut.html)perldoc(http://perldoc.perl.org)page.
Python Forfurtherreading
EmbeddedSystems/MixedCandAssemblyProgramming
References
1. 2. 3. 4. Lesson:47fromNeHeProductions(http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=47) CgBumpmappingbyRazvanSurdulescuatGameDev(http://www.gamedev.net/reference/articles/article1903.asp) [http://www.fusionindustries.com/default.asp?page=cghlslfaq|Cg&HLSLShadingLanguageFAQbyFusionIndustries] http://http.developer.nvidia.com/CgTutorial/cg_tutorial_appendix_b.htmlNVidiaCgtutorial.AppendixB.TheCgRuntime
Codelibrary
ThefollowingisanimplementationoftheStandardC99versionof < a s s e r t . h > :
/ *a s s e r t . hh e a d e r* / # u n d e fa s s e r t # i f d e fN D E B U G # d e f i n ea s s e r t ( _ I g n o r e )( ( v o i d ) 0 ) # e l s e v o i d_ A s s e r t f a i l ( c h a r* ,c h a r* ,i n t ,c h a r* ) ; # d e f i n ea s s e r t ( _ T e s t )( ( _ T e s t ) ? ( ( v o i d ) 0 ) : _ A s s e r t f a i l ( # _ T e s t , _ _ F I L E _ _ , _ _ L I N E _ _ , _ _ f u n c _ _ ) ) # e n d i f / *E N DO FF I L E* / / *x a s s e r t f a i l . c-_ A s s e r t f a i lf u n c t i o n* / # i n c l u d e< s t d l i b . h > # i n c l u d e< s t d i o . h > # i n c l u d e< a s s e r t . h > v o i d _ A s s e r t f a i l ( c h a r* t e s t ,c h a r* f i l e n a m e ,i n tl i n e _ n u m b e r ,c h a r* f u n c t i o n _ n a m e ) { f p r i n t f ( s t d e r r ," A s s e r t i o nf a i l e d :% s ,f u n c t i o n% s ,f i l e% s ,l i n e% d . " , t e s t ,f u n c t i o n _ n a m e ,f i l e n a m e ,l i n e _ n u m b e r ) ; a b o r t ( ) ; } / *E N DO FF I L E* /
ComputerProgramming
ThefollowingarticlesareCadaptationsfromarticlesoftheComputerprogrammingbook.
Statements
A statementisacommandgiventothecomputerthatinstructsthecomputertotakeaspecificaction,suchasdisplaytothescreen,orcollectinput.Acomputerprogramismadeupofaseriesofstatements.
p u t s( " H it h e r e ! " ) ;
en.wikibooks.org/wiki/C_Programming/Print_version
111/118
10/24/13
CReferenceTables
ThissectionhassometablesandlistsofCentities.
ReferenceTables
ListofKeywords
ANSIC(C89)/ISOC(C90)keywords:
a u t o b r e a k c a s e c h a r c o n s t c o n t i n u e d e f a u l t d o
d o u b l e e l s e e n u m e x t e r n f l o a t f o r g o t o i f
i n t l o n g r e g i s t e r r e t u r n s h o r t s i g n e d s i z e o f s t a t i c
s t r u c t s w i t c h t y p e d e f u n i o n u n s i g n e d v o i d v o l a t i l e w h i l e
KeywordsaddedtoISOC(C99)(Supportedonlyinnewcompilers):
_ B o o l _ C o m p l e x
_ I m a g i n a r y i n l i n e
r e s t r i c t( h t t p : / / e n . w i k i p e d i a . o r g / w i k i / R e s t r i c t )
ListofStandardHeaders
ANSIC(C89)/ISOC(C90)headers:
Veryoldcompilersmaynotincludesomeorallofthefollowingheaders: HeadersaddedtoISOC(C94/C95)inAmendment1(AMD1):
< i s o 6 4 6 . h >
< w c h a r . h >
< w c t y p e . h >
HeadersaddedtoISOC(C99)(Supportedonlyinnewcompilers):
en.wikibooks.org/wiki/C_Programming/Print_version
112/118
10/24/13
TableofOperators
Operatorsinthesamerowofthistablehavethesame precedenceandtheorderofevaluationisdecidedbythe associativity(lefttoright or righttoleft ).Operatorsclosertothetopofthistablehave higherprecedencethanthoseinasubsequent group. Operators Description Postfixoperators ExampleUsage Associativity
( ) [ ]
s w a p( x ,y ) a r r[ i ]
Lefttoright
o b j . m e m b e r
>
p t r > m e m b e r
UnaryOperators
! ~
! e o f _ r e a c h e d ~ m a s k n u m
[1] ++ ++ +& * s i z e o f s i z e o f ( ) ( t y p e )
Righttoleft
MultiplicativeOperators
*/%
multiplication,divisionand modulusoperators
Lefttoright
c e l s i u s _ d i f f*9 . 0/5 . 0
AdditiveOperators
+-
Lefttoright
e n d-s t a r t+1
additionandsubtractionoperators
BitwiseShiftOperators Lefttoright
< < > >
leftshiftoperator rightshiftoperator
RelationalInequalityOperators
en.wikibooks.org/wiki/C_Programming/Print_version
113/118
10/24/13
<>< => =
RelationalEqualityOperators
= =! =
equalto,notequalto
Lefttoright
c h o i c e! =' n '
BitwiseAndOperator
& b i t s&c l e a r _ m a s k _ c o m p l e m e n t
Lefttoright
BitwiseXorOperator
^ b i t s^i n v e r t _ m a s k
Lefttoright
BitwiseOrOperator
| b i t s|s e t _ m a s k
Lefttoright
LogicalAndOperator
& & a r r! =0& &a r r > l e n! =0
Lefttoright
LogicalOrOperator
| |
seeLogicalExpressions ConditionalOperator
Lefttoright
a r r= =0| |a r r > l e n= =0
Righttoleft
? : s i z e! =0?s i z e:0
AssignmentOperators
= + ==* =/ = % =& =| =^ = < < => > =
i=0
Righttoleft
n u m/ =1 0
CommaOperator
, i=0 ,j=i+1 ,k=0
Lefttoright
TableofOperatorsFootnotes
[1]Veryoldcompilersmaynotrecognizetheunary + operator.
TableofDataTypes
Type SizeinBits Comments PrimitiveTypesinANSIC(C89)/ISOC(C90) AlternativeNames
en.wikibooks.org/wiki/C_Programming/Print_version
114/118
10/24/13
s i g n e dc h a r
sameas c h a r
Charactersstoredlikefortype c h a r . Canstoreintegersintherange127~127portably[1].
u n s i g n e dc h a r
sameas c h a r
Charactersstoredlikefortype c h a r . Canstoreintegersintherange0~255portably.
s h o r t
16,sizeof c h a r
Canstoreintegersintherange32767~32767portably[2]. Usedtoreducememoryusage(althoughtheresultingexecutablemaybelargerandprobablyslowerascomparedtousing i n t .
s h o r ti n t , s i g n e ds h o r t , s i g n e ds h o r t i n t
u n s i g n e ds h o r t
sameas s h o r t
Canstoreintegersintherange0~65535portably. Usedtoreducememoryusage(althoughtheresultingexecutablemaybelargerandprobablyslowerascomparedtousing i n t .
u n s i g n e ds h o r ti n t
i n t
16,sizeof s h o r t
Representsthe"normal"sizeofdatatheprocessordealswith(thewordsize)thisistheintegraldatatypeusednormally. Canstoreintegersintherange32767~32767portably[2].
s i g n e d , s i g n e di n t
u n s i g n e di n t
sameas i n t
Canstoreintegersintherange0~65535portably.
u n s i g n e d
l o n g
32,sizeof i n t
Canstoreintegersintherange2147483647~2147483647portably[3].
l o n gi n t , s i g n e dl o n g , s i g n e dl o n gi n t
u n s i g n e dl o n g
sameas l o n g
Canstoreintegersintherange0~4294967295portably.
u n s i g n e dl o n gi n t
f l o a t
sizeof c h a r
d o u b l e
sizeof f l o a t
l o n gd o u b l e
sizeof d o u b l e
u n s i g n e d cannotbespecified.
en.wikibooks.org/wiki/C_Programming/Print_version
115/118
10/24/13
PrimitiveTypesaddedtoISOC(C99)
l o n gl o n gi n t , s i g n e dl o n gl o n g , s i g n e d l o n gl o n gi n t
l o n gl o n g
64,sizeof l o n g
Canstoreintegersintherange9223372036854775807~9223372036854775807portably[4].
u n s i g n e dl o n gl o n g
sameas l o n gl o n g
Canstoreintegersintherange0~18446744073709551615portably.
u n s i g n e dl o n gl o n gi n t
i n t m a x _ t
themaximumwidthsupportedby theplatform
Canstoreintegersintherange(1<<n1)+1~(1<<n1)1,with'n'thewidthofintmax_t. Usedbythe"j"lengthmodifierintheCProgramming/FileIO#Formattedoutputfunctions:theprintffamilyoffunctions.
u i n t m a x _ t
sameas i n t m a x _ t
Canstoreintegersintherange0~(1<<n)1,with'n'thewidthofuintmax_t.
UserDefinedTypes
s t r u c t
sumofsizeofeachmember
Saidtobean aggregatetype.
u n i o n
sizeofthelargestmember
Saidtobean aggregatetype.
e n u m
sizeof c h a r
Enumerationsareaseparatetypefrom i n t s,thoughtheyaremutuallyconvertible.
t y p e d e f
sameasthetypebeinggivena name
t y p e d e f hassyntaxsimilartoastorageclasslike s t a t i c , r e g i s t e r or e x t e r n .
DerivedTypes[5]
0 alwaysrepresentsthenullpointer(anaddresswherenodatacanbeplaced),irrespectiveofwhatbitsequencerepresentsthe
t y p e *
sizeof c h a r (pointer)
[ 6 ] t y p e[ i n t e g e r ]
en.wikibooks.org/wiki/C_Programming/Print_version
116/118
10/24/13
(array)
t y p e( c o m m a d e l i m i t e dl i s to f t y p e s / d e c l a r a t i o n s )
(function)
TableofDataTypesFootnotes
[1]128canbestoredintwo'scomplementmachines(i.e.mostmachinesinexistence).Veryoldcompilersmaynotrecognizethe s i g n e d keyword. [2]32768canbestoredintwo'scomplementmachines(i.e.mostmachinesinexistence).Veryoldcompilersmaynotrecognizethe s i g n e d keyword. [3]2147483648canbestoredintwo'scomplementmachines(i.e.mostmachinesinexistence).Veryoldcompilersmaynotrecognizethe s i g n e d keyword. [4]9223372036854775808canbestoredintwo'scomplementmachines(i.e.mostmachinesinexistence). [5]Theprecedencesinadeclarationare:
[ ] , ( ) (leftassociative)Highest * (rightassociative)Lowest
[6]ThestandardsdoNOTplaceanyrestrictiononthesize/typeoftheinteger,it'simplementationdependent.Theonlymentioninthestandardsisareferencethatanimplementationmayhavelimitstothemaximumsizeofmemoryblockwhichcanbe
allocated,andassuchthelimitonintegerwillbesize_of_max_block/sizeof(type).
Compilers
Free(orwithafreeversion)
Ch_interpreter(http://www.softintegration.com)ThesoftwareworksinWindows,Linux,MacOSX,Freebsd,Solaris,AIXandHPUX.TheChStandardEditionisfreefornoncommercialuse. lccwin32(http://www.cs.virginia.edu/~lccwin32)SoftwarecopyrightedbyJacobNavia.Itisfreefornoncommercialuse.Windows(98/ME/XP/2000/NT). GNUCompilerCollection(http://gcc.gnu.org)GNUCompilerCollection.GNUGeneralPublicLicense/GNULesserGeneralPublicLicense. MinGW(http://www.mingw.org/)providesGCCforWindows OpenWatcom(http://www.openwatcom.org)OpenSourcedevelopmentcommunitytomaintainandenhancetheWatcomC/C++andFortrancrosscompilersandtools.Version1.4releasedinDecember2005. HostPlatforms:Win32systems(IDEandcommandline),32bitOS/2(IDEandcommandline),DOS(commandline),andWindows3.x(IDE) TargetPlatforms:DOS(16bit),Windows3.x(16bit),OS/21.x(16bit),ExtendedDOS,Win32s,Windows95/98/Me,WindowsNT/2000/XP,32bitOS/2,andNovellNLMs Experimental/Development:Linux,BSD,*nix,PowerPC,AlphaAXP,MIPS,andSparcv8 TinyCCompiler PortableCCompiler(http://pcc.ludd.ltu.se)PortableCCompiler.BSDStyleLicense(s). SmallDeviceCCompiler(SDCC) targetplatforms:Intel8051compatiblesFreescale(Motorola)HC08MicrochipPIC16andPIC18. FpgaC.Targetplatform:FPGAhardwareviaXNForVHDLfiles. InteractiveC(http://www.botball.org/educationalresources/ic.php). targetplatform:HandyBoard(Freescale68HC11)LegoRCX Ccompilersformanydigitalsignalprocessors(DSPs),manyofthemfree,arelistedinthecomp.dspFAQ(http://www.bdti.com/faq/3.htm).
Commercial
IntelCCompiler(http://software.intel.com/enus/intelcompilers)Windows,Linux,Mac,QNX,andembeddedC/C++compilers.OptimizedforIntel32bitand64bitCPUs. MicrosoftVisualC++(http://msdn.microsoft.com/visualc)Free(partiallylimited)versionavailable(Expressedition) ImpulseCTargetplatform:FPGAhardwareviaHardwareDescriptionLanguage(HDL)files. Retrievedfrom"http://en.wikibooks.org/w/index.php?title=C_Programming/Print_version&oldid=2361350"
en.wikibooks.org/wiki/C_Programming/Print_version
117/118
10/24/13
Thispagewaslastmodifiedon9June2012,at08:12.
TextisavailableundertheCreativeCommonsAttribution/ShareAlikeLicenseadditionaltermsmayapply.Byusingthissite,youagreetotheTermsofUseandPrivacyPolicy.
en.wikibooks.org/wiki/C_Programming/Print_version
118/118