You are on page 1of 118

10/24/13

C Programming/Print version - Wikibooks, open books for an open world

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

C Programming/Print version - Wikibooks, open books for an open world

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

Freefornoncommercial Smallopensourcecompiler. use

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/)

C Programming/Print version - Wikibooks, open books for an open world


MacOSX Windows,PocketPC Windows Windows Crossplatform Crossplatform Free Free GPL Free GPL2 GPL3.0 AvailableforfreeatMacAppStore (https://itunes.apple.com/us/app/xcode/id497799835?ls=1&mt=12). AcompleteCdevelopmentkitforWindows. UpdatedversionoftheformerlypopularBloodshedDevC++. Apowerful,userfriendlyversionofanindustrystandardcompiler. FreeIDEforC/C++development. Builttomeetusers'mostdemandingneeds.Veryextensibleandfullyconfigurable.

VisualC++(http://www.microsoft.com/visualstudio/enus/products/2010 editions/visualcppexpress) CodeLite(http://codelite.org/) Code::Blocks(http://codeblocks.org/)

On GNU/Linux,GCCisalmostalwaysincludedautomatically. On MicrosoftWindows,DevC++isrecommendedforbeginnersbecauseitiseasytouse,free,andsimpletoinstall.However,theofficialreleaseofDevC++hasn'tbeenupdatedsince22February2005. [2]Anunofficial (http://sourceforge.net/projects/orwelldevcpp/)versionofDevC++isbeingactivelydevelopedhowever. [3]AnalternateoptionforthoseworkingonlyintheWindowsenvironmentistheofficialMicrosoftVisualStudioExpresswhichisfreeandhasan excellentdebugger. On MacOSX ,theXcodeIDEprovidesthecompilersneededtocompilevarioussourcefiles.Thenewerversionsdonotnotincludethecommandlinetools.TheyneedtobedownloadedviaXcode>Preferences>Downloads.

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

C Programming/Print version - Wikibooks, open books for an open world

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

myfun.hisincludedinmain.c,butifisinaseparateheaderfilesdirectory,thenthatdirectorycanbelistedaftera"I"switch. Inlargerprograms,Makefilesandgnumakeprogramcancompilecfilesintointermediatefilesendingwithsuffix.owhichcanbelinkedbygcc. HowtocompileeachobjectfileisusuallydescribedintheMakefilewiththeobjectfileasalabelendingwithacolonfollowedbytwospaces(tabsareoftenbadcharacters)followedbyalistofotherfilesthataredependencies,eg..cfilesand.ofiles compiledinanothersection,andonthenextline,theinvocationofgccthatisrequired.typingmanmakeorinfomakeoftengivestheinformationneededtojogthememoryonhowtousemake,andthesamegoesforgcc,althoughgcchasalotof optionswitches,themainonesbeinggtogeneratedebuggingforgdbtoallowittoshowsourcecodeduringsteppingthroughofthemachinecodeprogram.gdbhasa'h'commandthatshowswhatitcando,andisusuallystartedwith'gdba.out'ifa.out istheanonymousexecutablemachinecodefilethatwascompiledbygcc.

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".

C Programming/Print version - Wikibooks, open books for an open world

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

functionineveryfile.The int atthebeginningmeansthatmainwillreturnanintegertotheoperatingsystemwhenitisfinished.


p u t s ( " H e l l o ,w o r l d ! " ) ; isthestatementthatactuallyputsthemessagetothescreen. putsisastringprintingfunctionthatisdeclaredinthefile stdio.h(whichiswhyyouhadto #includethatatthestartoftheprogram) p u t s automaticallyprintsanewlineat

theendofthestring.
r e t u r n0 ; willreturnzero(whichistheintegerreferredtoonline3)totheoperatingsystem.Whenaprogramrunssuccessfullyitsreturnvalueiszero(GCC4complainsifitdoesn'twhencompiling).Anonzerovalueisreturnedtoindicateawarningorerror.

Theemptylineistherebecauseitis(atleastonUNIX)consideredgoodpracticetoendafilewithanewline.Ingccusingthe W a l lp e d a n t i ca n s i options,ifthefiledoesnotendwithanewlinethismessageisdisplayed:"warning:nonewlineatendof file".(Thenewlineisn'tshownontheexamplebecauseMediaWikiautomaticallyremovesit)

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

C Programming/Print version - Wikibooks, open books for an open world

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.

# 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 (i n ta r g c ,c h a r * *a r g v ){ p r i n t f ( " H e l l oW O r l d !\ n " ) ; r e t u r n0 ; }

Thecommentedprogrambelowisbasicallythesame,withsomevariationsthathavethesameeffect.e.g.a"argv",or"pointertopointers",isthesameas*x[]or"arrayofpointers"and"exit(0)"doesthesameas"return0"forthemainfunction. Note:Itisagoodchancetosaythatweusuallyreturnorexitafunctionwiththe0codewhenallofthecommandsexecutedsuccessfully.e.g.inourHelloWorldprogram,allthecommandsbefore"return(0)",or"exit(0)"executedwithnoerror.Youwill noticethatthisconventionisverycommon,especiallyinthemainfunction.


/ *H e l l oW o r l d* / / * t h i sg i v e si n c l u d es t a t e m e n t ,b r i n g si nt h eh e a d e rf i l es t d i o . h, l o c a t e do f t e no nu n i xs y s t e m sa tt h ed i r e c t o r y/ u s r / i n c l u d e / , a n di n c l u d e s t h ep r i n t f ( )f u n c t i o n ,a sw e l la so t h e r s ,s n p r i n t f ,s c a n f ,g e t c h a r ,g e t l i n e . I nC ,f u n c t i o n st h a ta r ee x p o r t e dh a v et h e i r" s i g n a t u r e s "-f u n c t i o nn a m ea n dp a r a m e t e rl i s tl i s t e di nh e a d e rf i l e sf o re x p o r t i n g ,a n dt h e nt h es a m es i g n a t u r e sa r ed e f i n e di na n o t h e rf i l e , o f t e no ft h es a m en a m e ,t ob ec o m p i l e do n c ei n t oa no b j e c tf i l e ,a n do nu n i xs y s t e m so f t e nr e s i d e i n/ u s r / l i b / w i t hf i l en a m e sl i k es t d l i b . a o rs t d l i b . s o,o f t e na ss o f tl i n k st ov e r s i o n e df i l e s e . g .s t d l i b . 1 . 3 . s o, * / # i n c l u d e< s t d i o . h > / * t h i sg i v e st h es t a n d a r dl i b r a r y ,w h i c hh a sf u n c t i o n s s u c ha sr a n d ( )r a n d o mn u m b e rg e n e r a t i o n( e . g .f o rg a m e s ) m a l l o c ( )a n df r e e ( ) f o rd y n a m i ch e a pm e m o r ya l l o c a t i o na so p p o s e dt os t a c km e m o r ya l l o c a t i o n . s t a c km e m o r yc a nb ea l l o c a t e db yd e c l a r i n gv a r i a b l e sa n da r r a y sa tt h es t a r to faf u n c t i o n,i n c l u d i n g t h em a i nf u n c t i o n ,a n dw i l lb ed e s t r o y e dw h e nt h ef u n c t i o ne x i t s . * / # i n c l u d e< s t d l i b . h > / * t h en e x tl i n ei st h es t a n d a r de x p e c t e df u n c t i o nn a m e" m a i n "a n da r g u m e n tl i s to ft h ef i r s tf u n c t i o n t ob ee x e c u t e df o rt h i sp r o g r a mw h e nt h ec o m p i l e dp r o g r a mi se x e c u t e d . t h ef i r s ta r g u m e n ti st h en u m b e ro fa r g u m e n t s ,a n dt h es e c o n da r g u m e n ti sa na r r a yo fp o i n t e r st o a r r a y so fc h a r a c t e r s( s t r i n g s )w h i c hc o n t a i na r g u m e n t s. e . g . " ? "," v "," c " * / i n tm a i n ( i n tn _ a r g s ,c h a r *a r g s [ ] ){ p r i n t f ( " H e l l oW o r l d ! " ) ; / / o u t p u t sas t r i n gw i t h o u tf o r m a t t i n g . e x i t ( 0 ) ; / / s t d l i b . hf u n c t i o nt oe x i tw i t hac o d e ,i fe x e c u t e df r o m s a yab a s hs h e l ls c r i p t ,0w i l lb e / / r e t u r n e d ,w h i c hc a nb eu s e di n s i d eas h e l lc o n d i t i o n a li fs t a t e m e n t . }

OnIDEs
IfyouareusingacommercialIDEyoumayhavetoselectconsoleproject,andtocompileyoujustselectbuildfromthemenuorthetoolbar.Theexecutablewillappearinsidetheprojectfolder,butyoushouldhaveamenubuttonsoyoucanjustrunthe executablefromtheIDE. OnecanalsofindopensourceIDE'slikeEclipse,NetbeansorQtCreator.TheprocesswillbethesameasacommercialIDE.

en.wikibooks.org/wiki/C_Programming/Print_version

6/118

10/24/13

C Programming/Print version - Wikibooks, open books for an open world

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* /

Youmighthavenoticedthesemicolonattheendofthestatement.StatementsinCalwaysendwithasemicolon()character.Leavingoffthesemicolonisacommonmistakethatalotofpeoplemake,beginnersandexpertsalike!Sountilitbecomes secondnature,besuretodoublecheckyourstatements! SinceCisa"freeformat"language,severalstatementscanshareasinglelineinthesourcefile,likeso:


/ *t h i sd e c l a r e st h ev a r i a b l e s' i ' ,' t e s t ' ,' f o o ' ,a n d' b a r ' n o t et h a tO N L Y' b a r 'i ss e tt os i x !* / i n ti ,t e s t ,f o o ,b a r=6 ;

Thereareseveralkindsofstatements,andyou'veseensomeofthem.Assignment(i=6),conditionalandflowcontrol.Asubstantialportionofthisbookdealswithstatementconstruction. Nowbacktoblocks.InC,blocksbeginwithanopeningbrace " { " andendwithaclosingbrace " } " .Blockscancontainotherblockswhichcancontaintheirownblocks,andsoon. Let'sshowanexampleofblocks.


i n tm a i n ( v o i d ) { / *t h i si sa' b l o c k '* / i n ti=5 ; { / *t h i si sa l s oa' b l o c k , 's e p a r a t ef r o mt h el a s to n e* / i n ti=6 ; } r e t u r n0 ; }

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

C Programming/Print version - Wikibooks, open books for an open world

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

C Programming/Print version - Wikibooks, open books for an open world

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 >

Thisdirectivecausestheheadertobeincludedintoyourprogram.Otherdirectivessuchas # p r a g m a controlcompilersettingsandmacros.Theresultofthepreprocessingstageisatextstring.Youcanthinkofthepreprocessorasanoninteractivetexteditor thatpreparesyourcodeforthecompilationstep.ThelanguageofpreprocessordirectivesisagnostictothegrammarofC,sotheCpreprocessorcanalsobeusedindependentlytoprocessotherkindsoftextfiles.

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 ; }

C Programming/Print version - Wikibooks, open books for an open world

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 ; }

Thesimpleuseofindentsandlinebreakscangreatlyimprovethereadabilityofthecodewithoutmakinganyimpactwhatsoeveronhowthecodeperforms.Byhavingreadablecode,itismucheasiertoseewherefunctionsandproceduresend,and whichlinesarepartofwhichloopsandprocedures. Thisbookisgoingtofocusontheabovepieceofcode,andhowtoimproveit.Pleasenotethatduringthecourseofthetutorial,therewillbemany(apparently)redundantpiecesofcodeadded.Theseareonlyaddedtoprovideexamplesoftechniques thatwewillbeexplaining,withoutbreakingtheoverallflowofcodethattheprogramachieves.

LineBreaksandIndentation
Theadditionofwhitespaceinsideyourcodeisarguablythemostimportantpartofgoodcodestructure.Effectiveuseofwhitespacecancreateavisualscaleofhowyourcodeflows,whichcanbeveryimportantwhenreturningtoyourcodewhenyou wanttomaintainit.

LineBreaks
Withminimallinebreaks,codeisbarelyreadablebyhumans,andmaybehardtodebugorunderstand:

1 .# i n c l u d e< s t d i o . h > a i n i 2 .i n tm ( v o i d ) {i n ti = 0 ;p r i n t f ( " H e l l o ,W o r l d ! " ) ;f o r( = 0 ;i < 1 ;i + + ) {p r i n t f ( " \ n " ) ;b r e a k ;}r e t u r n0 ;}

Ratherthanputtingeverythingononeline,itismuchmorereadabletobreakuplonglinessothateachstatementanddeclarationgoesonitsownline.Afterinsertinglinebreaks,thecodewilllooklikethis:

1 .# i n c l u d e< s t d i o . h > a i n 2 .i n tm ( v o i d ) 3 .{ 4 .i n ti = 0 ; 5 .p r i n t f ( " H e l l o ,W o r l d ! " ) ; i 6 .f o r( = 0 ;i < 1 ;i + + ) 7 .{ 8 .p r i n t f ( " \ n " ) ; 9 .b r e a k ; 1 0 .} 1 1 .r e t u r n0 ; 1 2 .}

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 .}

C Programming/Print version - Wikibooks, open books for an open world

Butthisstillisn'tasreadableasitcanbe.

Indentation
Althoughaddingsimplelinebreaksbetweenkeyblocksofcodecanmakecodeeasiertoread,itprovidesnoinformationabouttheblockstructureoftheprogram.Usingthetabkeycanbeveryhelpfulnow:indentation visuallyseparatespathsofexecutionbymovingtheirstartingpointstoanewcolumnintheline.Thissimplepracticewillmakeitmucheasiertoreadandunderstandcode.Indentationfollowsafairlysimplerule:
Manytexteditors

Allcodeinsideanewblockshouldbeindentedbyonetab[1]morethanthecodeinthepreviouspath. Basedonthecodefromtheprevioussection,therearetwoblocksrequiringindentation: Lines5to13 Lines10and11

automaticallyindent appropriatelywhenyou hittheenter/returnkey.

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 .{ 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 .}

Itisnowfairlyobviousastowhichpartsoftheprogramfitinsidewhichblocks.Youcantellwhichpartsoftheprogramthecoderhasintendedtoloop,andwhichoneshehasnot.Althoughitmightnotbeimmediatelynoticeable,oncemanynestedloops andpathsgetaddedtothestructureoftheprogram,theuseofindentationcanbeveryimportant.Thisindentationmakesthestructureofyourprogramclear. Indentationwasoriginallyonetabcharacter,ortheequivalentof8spaces.Researchsincetheoriginalindentsizehasshownthatindentsbetween2to4charactersareeasiertoread[2],resultinginsuchtabsizesbeingusedasdefaultinmodernIDEs. However,anindentof8charactersmaystillbeinuseforsomesystems[3].

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

C Programming/Print version - Wikibooks, open books for an open world

Singlelinecommentsaremostusefulforsimple'side'notesthatexplainwhatcertainpartsofthecodedo.Thebestplacestoputthesecommentsarenexttovariabledeclarations,andnexttopiecesofcodethatmayneedexplanation. Basedonourpreviousprogram,therearetwogoodplacestoplacecomments Line5,toexplainwhat'inti'isgoingtodo Line11,toexplainwhythereisa'break'keyword. Thiswillmakeourprogramlooksomethinglike


# 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 = 0 ;

/ /l o o pv a r i a b l e .

p r i n t f ( " H e l l o ,W o r l d ! " ) ; f o r( i = 0 ;i < 1 ;i + + ){ p r i n t f ( " \ n " ) ; b r e a k ; } r e t u r n0 ; }

/ / E x i t s' f o r 'l o o p .

MultilineComments
Multilinecommentsaremostusefulforlongexplanationsofcode.Theycanbeusedascopyright/licensingnotices,andtheycanalsobeusedtoexplainthepurposeofablockofcode.Thiscanbeusefulfortworeasons: Theymakeyourfunctionseasiertounderstand,andtheymakeiteasiertospoterrorsincode.Ifyouknowwhatablockis supposedtodo,thenitismucheasiertofindthepieceofcodethatisresponsibleifanerroroccurs.
Singlelinecomments

Asanexample,supposewehadaprogramthatwasdesignedtoprint"Hello,World!"acertainnumberoflines,aspecifiednumberoftimes.Therewouldbemanyforloopsinthisprogram.Forthisexample,weshallcall thenumberoflines i,andthenumberofstringsperlineas j. Agoodexampleofamultilinecommentthatdescribes'for'loop i'spurposewouldbe:


/ *F o rL o o p( i n ti ) L o o p st h ef o l l o w i n gp r o c e d u r eit i m e s( f o rn u m b e ro fl i n e s ) . P e r f o r m s' f o r 'l o o pjo ne a c hl o o p , a n dp r i n t san e wl i n ea te n do fe a c hl o o p . * /

areanewfeature,so manyCprogrammers onlyusemultiline comments.

Thisprovidesagoodexplanationofwhat i'spurposeis,whilstnotgoingintodetailofwhat jdoes.Bygoingintodetailoverwhatthespecificpathdoes(andnotonesinsideit),itwillbeeasiertotroubleshootthepath. Similarly,youshouldalwaysincludeamultilinecommentbeforeeachfunction,toexplaintherole,preconditionsandpostconditionsofeachfunction.Alwaysleavethetechnicaldetailstotheindividualblocksinsideyourprogramthismakesiteasierto troubleshoot. Afunctiondescriptorshouldlooksomethinglike:


/ *F u n c t i o n:i n th w o r l d( i n ti , i n tj ) I n p u t :i n ti( N u m b e ro fl i n e s ) ,i n tj( N u m b e ro fi n s t a n c e sp e rl i n e ) O u t p u t :0( o 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 ! "jt i m e s ,a n dan e wl i n et os t a n d a r do u t p u to v e ril i n e s . * /

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 .

C Programming/Print version - Wikibooks, open books for an open world

p r i n t f ( " H e l l o ,W o r l d ! " ) ; / *F O RL O O P( i n ti ) P r i n t san e wl i n et os t a n d a r do u t p u t ,a n de x i t s* / f o r( i = 0 ;i < 1 ;i + + ) { p r i n t f ( " \ n " ) ; b r e a k ; / / E x i t s' f o r 'l o o p . } r e t u r n0 ; }

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* / }

C Programming/Print version - Wikibooks, open books for an open world

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 ; }

C Programming/Print version - Wikibooks, open books for an open world

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 ;

Thisstatementmeanswe'redeclaringsomespaceforavariablecalledsome_number,whichwillbeusedtostore i n t egerdata.Notethatwemustspecifythetypeofdatathatavariablewillstore.Therearespecifickeywordstodothiswe'lllookatthem inthenextsection. Multiplevariablescanbedeclaredwithonestatement,likethis:


i n ta 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 ;

Wecanalsodeclare andassignsomecontenttoavariableatthesametime.
i n ts o m e _ n u m b e r = 3 ;

Thisiscalled initialization. InearlyversionsofC,variableshadtobedeclaredatthebeginningofablock.InC99itisallowedtomixdeclarationsandstatementsarbitrarilybutdoingsoisnotusual,becauseitisrarelynecessary,somecompilersstilldontsupportC99(portability), anditmay,becauseitisuncommonyet,irritatefellowprogrammers(maintainability).

en.wikibooks.org/wiki/C_Programming/Print_version

15/118

10/24/13

C Programming/Print version - Wikibooks, open books for an open world

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 ;

Thisisbecausetheassignment x=y returnsthevalueoftheassignment. x=y=z isreallyshorthandfor x=( y=z ) .

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 )

Asthelastexamplesuggests,certainwordsarereservedaskeywordsinthelanguage,andthesecannotbeusedasvariablenames. Inadditiontherearecertainsetsofnamesthat,whilenotlanguagekeywords,arereservedforonereasonoranother.Forexample,aCcompilermightusecertainnames"behindthescenes",andthismightcauseproblemsforaprogramthatattemptsto usethem.Also,somenamesarereservedforpossiblefutureuseintheCstandardlibrary.Therulesfordeterminingexactlywhatnamesarereserved(andinwhatcontextstheyarereserved)aretoocomplicatedtodescribehere,andasabeginneryou don'tneedtoworryaboutthemmuchanyway.Fornow,justavoidusingnamesthatbeginwithanunderscorecharacter. ThenamingrulesforCvariablesalsoapplytonamingotherlanguageconstructssuchasfunctionnames,structtags,andmacros,allofwhichwillbecoveredlater.

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

C Programming/Print version - Wikibooks, open books for an open world

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 ' ;

Thisis goodprogrammingpracticeinthatitallowsapersonreadingyourcodetounderstandthatletter1isbeinginitializedwiththeletter'a'tostartoffwith. Thesecondway,whichshould not beusedwhenyouarecodinglettercharacters,istowrite


c h a rl e t t e r 2=9 7 ;/ *i nA S C I I ,9 7=' 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

doubles.Examplesare:3.1415926f,4.0f,6.022e+23f. f l o a t variablescanbedeclaredusingthe f l o a t keyword.

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 )

Thetwoexpressionsabovereturnthesizeoftheobjectandtypespecified,inbytes.Thereturntypeis s i z e _ t (definedintheheader < s t d d e f . h > )whichisanunsignedvalue.Here'sanexampleusage:


s i z e _ ts i z e ; i n ti ; s i z e=s i z e o f ( i ) ;
s i z e willbesetto4,assuming C H A R _ B I T isdefinedas8,andanintegeris32bitswide.Thevalueof s i z e o f 'sresultisthenumberofbytes.

Notethatwhen s i z e o f isappliedtoa c h a r ,theresultis1thatis:

en.wikibooks.org/wiki/C_Programming/Print_version

17/118

10/24/13
s i z e o f ( c h a r )

C Programming/Print version - Wikibooks, open books for an open world

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

Whenyouwriteprograms,youcancreatewhatisknownasa macro,sowhenthecomputerisreadingyourcode,itwillreplaceallinstancesofawordwiththespecifiedexpression. Here'sanexample.Ifyouwrite


# d e f i n eP R I C E _ O F _ C O R N0 . 9 9

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

C Programming/Print version - Wikibooks, open books for an open world

IntheBasicConceptssection,theconceptofscopewasintroduced.Itisimportanttorevisitthedistinctionbetweenlocaltypesandglobaltypes,andhowtodeclarevariablesofeach.Todeclarealocalvariable,youplacethedeclarationatthebeginning (i.e.beforeanynondeclarativestatements)oftheblocktowhichthevariableisintendedtobelocal.Todeclareaglobalvariable,declarethevariableoutsideofanyblock.Ifavariableisglobal,itcanberead,andwritten,fromanywhereinyourprogram. Globalvariablesarenotconsideredgoodprogrammingpractice,andshouldbeavoidedwheneverpossible.Theyinhibitcodereadability,createnamingconflicts,wastememory,andcancreatedifficulttotracebugs.Excessiveusageofglobalsisusuallya signoflazinessand/orpoordesign.However,ifthereisasituationwherelocalvariablesmaycreatemoreobtuseandunreadablecode,there'snoshameinusingglobals.

OtherModifiers
Includedhere,forcompleteness,aremoreofthemodifiersthatstandardCprovides.Forthebeginningprogrammer, staticand externmaybeuseful. volatileismoreofinteresttoadvancedprogrammers. registerand autoarelargelydeprecatedandare generallynotofinteresttoeitherbeginningoradvancedprogrammers.

static
s t a t i c issometimesausefulkeyword.Itisacommonmisbeliefthattheonlypurposeistomakeavariablestayinmemory.

Whenyoudeclareafunctionorglobalvariableas staticitwillbecomeinternal.Youcannotaccessthefunctionorvariablethroughtheextern(seebelow)keywordfromotherfilesinyourproject. Whenyoudeclarealocalvariableas static,itiscreatedjustlikeanyothervariable.However,whenthevariablegoesoutofscope(i.e.theblockitwaslocaltoisfinished)thevariablestaysinmemory,retainingitsvalue.Thevariablestaysinmemoryuntil theprogramends.Whilethisbehaviourresemblesthatofglobalvariables,staticvariablesstillobeyscoperulesandthereforecannotbeaccessedoutsideoftheirscope. Variablesdeclaredstaticareinitializedtozero(orforpointers,NULL)bydefault. Youcanusestaticin(atleast)twodifferentways.Considerthiscode,andimagineitisinafilecalledjfile.c:


# i n c l u d e< s t d i o . h > s t a t i ci n tj=0 ; v o i du p ( v o i d ) { / *ki ss e tt o0w h e nt h ep r o g r a ms t a r t s .T h el i n ei st h e n" i g n o r e d " *f o rt h er e s to ft h ep r o g r a m( i . e .ki sn o ts e tt o0e v e r yt i m eu p ( ) *i sc a l l e d ) * / s t a t i ci n tk=0 ; j + + ; k + + ; p r i n t f ( " u p ( )c a l l e d . k =% 2 d ,j =% 2 d \ n " ,k,j ) ; } v o i dd o w n ( v o i d ) { s t a t i ci n tk=0 ; j ; k ; p r i n t f ( " d o w n ( )c a l l e d .k =% 2 d ,j =% 2 d \ n " ,k,j ) ; } i n tm a i n ( v o i d ) { i n ti ; / *c a l lt h eu pf u n c t i o n3t i m e s ,t h e nt h ed o w nf u n c t i o n2t i m e s* / f o r( i =0 ;i<3 ;i + + ) u p ( ) ; f o r( i =0 ;i<2 ;i + + ) d o w n ( ) ; r e t u r n0 ; }

Thejvarisaccessiblebybothupanddownandretainsitsvalue.Thekvarsalsoretaintheirvalue,buttheyaretwodifferentvariables,oneineachoftheirscopes.Staticvarsareagoodwaytoimplementencapsulation,atermfromtheobjectoriented wayofthinkingthateffectivelymeansnotallowingchangestobemadetoavariableexceptthroughfunctioncalls. Runningtheprogramabovewillproducethefollowingoutput:


u p ( )c a l l e d . k = 1 ,j = u p ( )c a l l e d . k = 2 ,j = u p ( )c a l l e d . k = 3 ,j = d o w n ( )c a l l e d .k =1 ,j = d o w n ( )c a l l e d .k =2 ,j = 1 2 3 2 1

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

C Programming/Print version - Wikibooks, open books for an open world

e x t e r n isusedwhenafileneedstoaccessavariableinanotherfilethatitmaynothave # i n c l u d e ddirectly.Therefore, externdoesnotactuallycarveoutspaceforanewvariable,itjustprovidesthecompilerwithsufficientinformationtoaccesstheremote

variable. Featuresof e x t e r n a l variable:


1 .K e y w o r du s e d -e x t e r n 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 -G l o b a l( a l lo v e rt h ep r o g r a m ) 5 .L i f e t i m e -V a l u ep e r s i s t st i l lt h ep r o g r a m ' se x e c u t i o nc o m e st oa ne n d 6 .K e y w o r do p t i o n a l i t y-O p t i o n a li fd e c l a r e do u t s i d ea l lt h ef u n c t i o n s

volatile
v o l a t i l e isaspecialtypeofmodifierwhichinformsthecompilerthatthevalueofthevariablemaybechangedbyexternalentitiesotherthantheprogramitself.Thisisnecessaryforcertainprogramscompiledwithoptimizationsifavariablewerenot

defined v o l a t i l e thenthecompilermayassumethatcertainoperationsinvolvingthevariablearesafetooptimizeawaywheninfacttheyaren't. volatileisparticularlyrelevantwhenworkingwithembeddedsystems(whereaprogrammaynothavecomplete controlofavariable)andmultithreadedapplications.

auto
a u t o isamodifierwhichspecifiesan"automatic"variablethatisautomaticallycreatedwheninscopeanddestroyedwhenoutofscope.Ifyouthinkthissoundslikeprettymuchwhatyou'vebeendoingallalongwhenyoudeclareavariable,you'reright:all

declareditemswithinablockareimplicitly"automatic".Forthisreason,the autokeywordismoreliketheanswertoatriviaquestionthanausefulmodifier,andtherearelotsofverycompetentprogrammersthatareunawareofitsexistence. Featuresof a u t o m a t i c variables:


1 .K e y w o r du s e d -a u t o 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 -G a r b a g ev a l u e( r a n d o mv a l u e ) 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 f i n e d 5 .L i f e t i m e -V a l u ep e r s i s t sw h i l et h ec o n t r o lr e m a i n sw i t h i nt h eb l o c k 6 .K e y w o r do p t i o n a l i t y-O p t i o n a l

register
r e g i s t e r isahinttothecompilertoattempttooptimizethestorageofthegivenvariablebystoringitinaregisterofthecomputer'sCPUwhentheprogramisrun.Mostoptimizingcompilersdothisanyway,souseofthiskeywordisoftenunnecessary.In

fact,ANSICstatesthatacompilercanignorethiskeywordifitsodesiresandmanydo.MicrosoftVisualC++isanexampleofanimplementationthatcompletelyignoresthe registerkeyword. Featuresof r e g i s t e r variables:


1 .K e y w o r du s e d -r e g i s t e r 2 .S t o r a g e -C P Ur e g i s t e r s( v a l u e sc a nb er e t r i e v e df a s t e rt h a nf r o mm e m o r y ) 3 .D e f a u l tv a l u e -G a r b a g ev a l u e 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 f i n e d 5 .L i f e t i m e -V a l u ep e r s i s t sw h i l et h ec o n t r o lr e m a i n sw i t h i nt h eb l o c k 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

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

C Programming/Print version - Wikibooks, open books for an open world

Thesesuppliesandreturnsofinformationtoacomputerarecalled inputand output.'Input'isinformationsuppliedtoacomputerorprogram.'Output'isinformationprovidedbyacomputerorprogram.Frequently,computerprogrammerswilllumpthe discussioninthemoregeneralterm input/output orsimply, I/O. InC,therearemanydifferentwaysforaprogramtocommunicatewiththeuser.Amazingly,themostsimplemethodsusuallytaughttobeginningprogrammersmayalsobethemostpowerful.Inthe"Hello,World"exampleatthebeginningofthistext, wewereintroducedtoaStandardLibraryfilestdio.h,andoneofitsfunctions,printf().Herewediscussmoreofthefunctionsthatstdio.hgivesus.

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 " ) ;

C Programming/Print version - Wikibooks, open books for an open world

butherewearestuck! p r i n t f onlyprintsstrings!Thankfully,printfhasmethodsforprintingnumbers.Whatwedoisputa placeholderformatcodeinthestring.Wewrite:


p r i n t f ( " 1 9 + 3 1i s% d " ,1 9 + 3 1 ) ;

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?

Whatwecandoisusethenewline escapecharacter.Anescapecharacterisaspecialcharacterthatwecanwritebutwilldosomethingspecialonscreen,suchasmakeabeep,writeatab,andsoon.Towriteanewlinewewrite \ n .Allescapecharacters startwithabackslash. Sotoachievetheoutputabove,wewrite


p r i n t f ( "1 9 0 5 \ n 3 1 2+ \ n \ n " ) ;

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 ; }

Thereareotherescapecharacterswecanuse.Anothercommononeistouse \ t towriteatab.Youcanuse \ a toringthecomputer'sbell,butyoushouldnotusethisverymuchinyourprograms,asexcessiveuseofsoundisnotveryfriendlytothe user.Media:CProgramming/Printversion

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

C Programming/Print version - Wikibooks, open books for an open world

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 ; }

Ifyouweretodescribetheeffectofthescanf()functioncallabove,itmightreadas:"Readinanintegerfromtheuserandstoreitattheaddressofvariable a". Ifyouaretryingtoinputa stringusing scanf ,youshould notincludethe&operator.Thecodebelowwillnotcompile.


s c a n f ( " % s " ,& a ) ;

Thecorrectusagewouldbe:
s c a n f ( " % s " ,a ) ;

Thisisbecause,wheneveryouuseaformatspecifierforastring(%s),thevariablethatyouusetostorethevaluewillbeanarrayand,thearraynames(inthiscasea)themselvespointouttotheirbaseaddressandhence,the addressofoperatoris notrequired. (Although,thisisvulnerabletoBufferoverflow.fgets()ispreferredtoscanf()). Noteoninputs:Whendataistypedatakeyboard,theinformationdoesnotgostraighttotheprogramthatisrunning.Itisfirststoredinwhatisknownasa bufferasmallamountofmemoryreservedfortheinputsource.Sometimestherewillbedata leftinthebufferwhentheprogramwantstoreadfromtheinputsource,andthescanf()functionwillreadthisdatainsteadofwaitingfortheusertotypesomething.Somemaysuggestyouusethefunctionfflush(stdin),whichmayworkasdesiredon somecomputers,butisn'tconsideredgoodpractice,asyouwillseelater.Doingthishasthedownfallthatifyoutakeyourcodetoadifferentcomputerwithadifferentcompiler,yourcodemaynotworkproperly.

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.

C Programming/Print version - Wikibooks, open books for an open world

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

Thekeyword s i z e o f followedbyaunaryexpressionisaunaryexpression.Thevalueisthesizeofthetypeoftheexpressioninbytes.Theexpressionisnotevaluated. Thekeyword s i z e o f followedbyaparenthesizedtypenameisaunaryexpression.Thevalueisthesizeofthetypeinbytes.

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 ; }

C Programming/Print version - Wikibooks, open books for an open world

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 ) ) ;

andcompileittoasingle32bitrotateinstruction. [1] [2] Onsomesystems,thismaybe"#define"edasamacroordefinedasaninlinefunctioncalledsomethinglike"rightrotate32"or"rotr32"or"ror32"inastandardheaderfilelike"bitops.h". [3]

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 ) ) ;

C Programming/Print version - Wikibooks, open books for an open world

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.

i n tx=7 ; i n ty=5 ; i f ( x= =7& &y= =5 ){ . . . }

Here,the&&operatorcheckstheleftmostexpression,thentheexpressiontoit'sright.Sincebothstatementsreturntrue,the&&operatorreturnstrue,andthecodeblockisexecuted.

i f ( x= =5& &y= =5 ){ . . . }

The&&operatorchecksinthesamewayasbefore,andfindsthatthefirstexpressionisfalse.The&&operatorstopsevaluatingassoonasitfindsastatementtobefalse,andreturnsafalse.
| | isusedtoevaluateexpressionslefttoright,andreturnsa1if eitheroftheexpressionsaretrue.

/ *U s et h es a m ev a r i a b l e sa sb e f o r e .* / i f ( x= =2| |y= =5 ){/ /t h e| |s t a t e m e n tc h e c k sb o t he x p r e s s i o n s ,f i n d st h a tt h el a t t e ri st r u e ,a n dr e t u r n st r u e . . . }

The | | operatorherecheckstheleftmostexpression,findsitfalse,butcontinuestoevaluatethenextexpression.Itfindsthatthenextexpressionreturnstrue,stops,andreturnsa1.Muchhowthe & & operatorceaseswhenitfindsanexpressionthat returnsfalse,the | | operatorceaseswhenitfindsanexpressionthatreturnstrue. ItisworthnotingthatCdoesnothaveBooleanvalues(trueandfalse)commonlyfoundinotherlanguages.Itinsteadinterpretsa0asfalse,andanynonzerovalueastrue.

Conditionaloperators
Theternary ? : operatoristheconditionaloperator.Theexpression ( x?y:z ) hasthevalueof y if x isnonzero, z otherwise. Example:

i n tx=0 ; i n ty ; y=( x?1 0 : 6 ) ;

en.wikibooks.org/wiki/C_Programming/Print_version

26/118

10/24/13

C Programming/Print version - Wikibooks, open books for an open world

Theexpression x evaluatesto0.Theternaryoperatorthenlooksforthe"iffalse"value,whichinthiscase,is6.Itreturnsthat,so y isequaltosix.Had x beenanonzero,thentheexpressionwouldhavereturneda10.

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* /

/ *t h i sl o o pi n i t i a l i z e sxa n dit o0 ,t h e nr u n st h el o o p* / f o r ( x=0 ,i=0 ;i< =6 ;i + + ){ p r i n t f ( " x=% d ,a n di=% d \ n " ,x ,i ) ; }

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* /

Thea t a n anda t a n 2 functions


The a t a n functionsreturnthearctangentoftheirargumentsinradians,andthe a t a n 2 functionreturnthearctangentof y / x inradians.The a t a n functionsreturnavalueintherange[/2,+/2](thereasonwhy/2areincludedintherangeisbecausethe floatingpointvaluemayrepresentinfinity,andatan()=/2)the a t a n 2 functionsreturnavalueintherange[/2,+/2].For a t a n 2 ,adomainerrormayoccurifbothargumentsarezero.

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* /

C Programming/Print version - Wikibooks, open books for an open world

Thec o s ,s i n ,andt a n functions


The c o s , s i n ,and t a n functionsreturnthecosine,sine,andtangentoftheargument,expressedinradians.
# i n c l u d e< m a t h . h > f l o a tc o s f ( f l o a tx ) ;/ *C 9 9* / f l o a ts i n f ( f l o a tx ) ;/ *C 9 9* / f l o a tt a n f ( f l o a tx ) ;/ *C 9 9* / d o u b l ec o s ( d o u b l ex ) ; d o u b l es i n ( d o u b l ex ) ; d o u b l et a n ( d o u b l ex ) ; l o n gd o u b l ec o s l ( l o n gd o u b l ex ) ;/ *C 9 9* / l o n gd o u b l es i n l ( l o n gd o u b l ex ) ;/ *C 9 9* / l o n gd o u b l et a n l ( 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

C Programming/Print version - Wikibooks, open books for an open world

Thesefunctionsareheavilyusedinsoftwarefloatingpointemulators,butareotherwiserarelydirectlycalled. Insidethecomputer,eachfloatingpointnumberisrepresentedbytwoparts: Thesignificandiseitherintherange[1/2,1),oritequalszero. Theexponentisaninteger. Thevalueofafloatingpointnumber is .

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)

Thel o g ,l o g 2 ,l o g 1 p ,andl o g 1 0 functions


The l o g functionscomputethebaseenatural(notcommon)logarithmoftheargumentandreturntheresult.Adomainerroroccursiftheargumentisnegative.Arangeerrormayoccuriftheargumentiszero. The l o g 1 p functionscomputethebaseenatural(notcommon)logarithmofoneplustheargumentandreturntheresult.Adomainerroroccursiftheargumentislessthan1.Arangeerrormayoccuriftheargumentis1. The l o g 1 0 functionscomputethecommon(base10)logarithmoftheargumentandreturntheresult.Adomainerroroccursiftheargumentisnegative.Arangeerrormayoccuriftheargumentiszero. The l o g 2 functionscomputethebase2logarithmoftheargumentandreturntheresult.Adomainerroroccursiftheargumentisnegative.Arangeerrormayoccuriftheargumentiszero.
# i n c l u d e< m a t h . h > f l o a tl o g f ( f l o a tx ) ;/ *C 9 9* / d o u b l el o g ( d o u b l ex ) ; l o n gd o u b l el o g l ( l o n gd o u b l ex ) ;/ *C 9 9* / f l o a tl o g 1 p f ( f l o a tx ) ;/ *C 9 9* / d o u b l el o g 1 p ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l el o g 1 p l ( l o n gd o u b l ex ) ;/ *C 9 9* / f l o a tl o g 1 0 f ( f l o a tx ) ;/ *C 9 9* / d o u b l el o g 1 0 ( d o u b l ex ) ; l o n gd o u b l el o g 1 0 l ( l o n gd o u b l ex ) ;/ *C 9 9* / f l o a tl o g 2 f ( f l o a tx ) ;/ *C 9 9* / d o u b l el o g 2 ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l el o g 2 l ( l o n gd o u b l ex ) ;/ *C 9 9* /

Thei l o g b andl o g b functions


The i l o g b functionsextracttheexponentof x asasignedintvalue.If x iszero,theyreturnthevalue F P _ I L O G B 0 if x isinfinite,theyreturnthevalue I N T _ M A X if x isnotanumbertheyreturnthevalue F P _ I L O G B N A N otherwise,theyareequivalenttocallingthe corresponding l o g b functionandcastingthereturnedvaluetotype i n t .Arangeerrormayoccurif x iszero. F P _ I L O G B 0 and F P _ I L O G B N A N aremacrosdefinedin m a t h . h I N T _ M A X isamacrodefinedin l i m i t s . h .
l o g b ( x ) The l o g b functionsextracttheexponentof x asasignedintegervalueinfloatingpointformat.If x issubnormal,itistreatedasifitwerenormalizedthus,forpositivefinite x ,1 x F L T _ R A D I X < F L T _ R A D I X . F L T _ R A D I X istheradixforfloatingpointnumbers, definedinthe f l o a t . h header.

# 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* /

C Programming/Print version - Wikibooks, open books for an open world

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

C Programming/Print version - Wikibooks, open books for an open world

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* /

Then e a r b y i n t ,r i n t ,l r i n t ,andl l r i n t functions


The n e a r b y i n t functionsroundtheirargumenttoanintegervalueinfloatingpointformat,usingthecurrentroundingdirectionandwithoutraisingthe"inexact"floatingpointexception. The r i n t functionsaresimilartothe n e a r b y i n t functionsexceptthattheycanraisethe"inexact"floatingpointexceptioniftheresultdiffersinvaluefromtheargument. The l r i n t and l l r i n t functionsroundtheirargumentstothenearestintegervalueaccordingtothecurrentroundingdirection.Iftheresultisoutsidetherangeofvaluesofthereturntype,thenumericresultisundefinedandarangeerrormayoccurifthe magnitudeoftheargumentistoolarge.
# i n c l u d e< m a t h . h > f l o a tn e a r b y i n t f ( f l o a tx ) ;/ *C 9 9* / d o u b l en e a r b y i n t ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l en e a r b y i n t l ( l o n gd o u b l ex ) ;/ *C 9 9* / f l o a tr i n t f ( f l o a tx ) ;/ *C 9 9* / d o u b l er i n t ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l er i n t l ( l o n gd o u b l ex ) ;/ *C 9 9* / l o n gi n tl r i n t f ( f l o a tx ) ;/ *C 9 9* / l o n gi n tl r i n t ( d o u b l ex ) ;/ *C 9 9* / l o n gi n tl r i n t l ( l o n gd o u b l ex ) ;/ *C 9 9* / l o n gl o n gi n tl l r i n t f ( f l o a tx ) ;/ *C 9 9* / l o n gl o n gi n tl l r i n t ( d o u b l ex ) ;/ *C 9 9* / l o n gl o n gi n tl l r i n t l ( l o n gd o u b l ex ) ;/ *C 9 9* /

Ther o u n d ,l r o u n d ,andl l r o u n d functions


The r o u n d functionsroundtheargumenttothenearestintegervalueinfloatingpointformat,roundinghalfwaycasesawayfromzero,regardlessofthecurrentroundingdirection. The l r o u n d and l l r o u n d functionsroundtheargumenttothenearestintegervalue,roundinghalfwaycasesawayfromzero,regardlessofthecurrentroundingdirection.Iftheresultisoutsidetherangeofvaluesofthereturntype,thenumericresultis undefinedandarangeerrormayoccurifthemagnitudeoftheargumentistoolarge.
# i n c l u d e< m a t h . h > f l o a tr o u n d f ( f l o a tx ) ;/ *C 9 9* / d o u b l er o u n d ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l er o u n d l ( l o n gd o u b l ex ) ;/ *C 9 9* / l o n gi n tl r o u n d f ( f l o a tx ) ;/ *C 9 9* / l o n gi n tl r o u n d ( d o u b l ex ) ;/ *C 9 9* / l o n gi n tl r o u n d l ( l o n gd o u b l ex ) ;/ *C 9 9* / l o n gl o n gi n tl l r o u n d f ( f l o a tx ) ;/ *C 9 9* / l o n gl o n gi n tl l r o u n d ( d o u b l ex ) ;/ *C 9 9* / l o n gl o n gi n tl l r o u n d l ( l o n gd o u b l ex ) ;/ *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

C Programming/Print version - Wikibooks, open books for an open world

The r e m q u o functionsreturnthesameremainderasthe r e m a i n d e r functions.Intheobjectpointedtoby q u o ,theystoreavaluewhosesignisthesignof x /y andwhosemagnitudeiscongruentmodulo2ntothemagnitudeoftheintegralquotientof x /y ,where n isanimplementationdefinedintegergreaterthanorequalto3.


# i n c l u d e< m a t h . h > f l o a tr e m q u o f ( f l o a tx ,f l o a ty ,i n t* q u o ) ;/ *C 9 9* / d o u b l er e m q u o ( d o u b l ex ,d o u b l ey ,i n t* q u o ) ;/ *C 9 9* / l o n gd o u b l er e m q u o l ( l o n gd o u b l ex ,l o n gd o u b l ey ,i n t* q u o ) ;/ *C 9 9* /

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

C Programming/Print version - Wikibooks, open books for an open world

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 }

Often # d e f i n eT R U E1 and # d e f i n eF A L S E0 areusedtoworkaroundthelackofabooleantype.Thisisbadpractice,sinceitmakesassumptionsthatdonothold.Itisabetterideatoindicatewhatyouareactuallyexpectingasaresultfromafunctioncall,as therearemanydifferentwaysofindicatingerrorconditions,dependingonthesituation.


i f( s t r s t r ( " f o o " ,b a r )> =0 ){ / / b a rc o n t a i n s" f o o " }

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 ) ) ;

C Programming/Print version - Wikibooks, open books for an open world

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 ){ . . . .

Inthesnippetofcode,thecomparisonofiwith12isdonefirst.Ifitevaluatesto0(false), i wouldbeoutofboundsasanindexto myArray.Inthiscase,theprogramneverattemptstoaccess myArray[i]sincethetruthoftheexpressionisknowntobe false.Henceweneednotworryhereabouttryingtoaccessanoutofboundsarrayelementifitisalreadyknownthatiisgreaterthanorequaltozero.Asimilarthinghappenswithexpressionsinvolvingtheor||operator.


w h i l e (d o T h i s ( )| |d o T h a t ( ) ). . .

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

C Programming/Print version - Wikibooks, open books for an open world

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* / }

C Programming/Print version - Wikibooks, open books for an open world

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 ; }

Ifa default caseisspecified,theassociatedstatementsareexecutedifnoneoftheothercasesmatch.A default caseisoptional.Here'saswitchstatementthatcorrespondstothesequenceofifelseifstatementsabove. Backtoourexampleabove.Here'swhatitwouldlooklikeasSwitchCase:


s w i t c h( g r a d e ){ c a s e1 : p r i n t f ( " A \ n " ) ; b r e a k ; c a s e2 : p r i n t f ( " B \ n " ) ; b r e a k ; c a s e3 : p r i n t f ( " C \ n " ) ; b r e a k ; c a s e4 : p r i n t f ( " D \ n " ) ; b r e a k ; d e f a u l t : p r i n t f ( " F \ 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 ; }

C Programming/Print version - Wikibooks, open books for an open world

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 ; }

Theflowofallloopscanalsobecontrolledby breakand continuestatements.Abreakstatementwillimmediatelyexittheenclosingloop.Acontinuestatementwillskiptheremainderoftheblockandstartatthecontrollingconditionalstatementagain. Forexample:


i n ta = 1 ; w h i l e( 4 2 ){/ /l o o p su n t i lt h eb r e a ks t a t e m e n ti nt h el o o pi se x e c u t e d p r i n t f ( " ai s% d" , a ) ; a=a * 2 ; i f ( a > 1 0 0 ){ b r e a k ; }e l s ei f ( a = = 6 4 ){ c o n t i n u e ; / /I m m e d i a t e l yr e s t a r t sa tw h i l e ,s k i p sn e x ts t e p } p r i n t f ( " ai sn o t6 4 \ n " ) ; }

Inthisexample,thecomputerprintsthevalueofaasusual,andprintsanoticethataisnot64(unlessitwasskippedbythecontinuestatement). SimilartoIfabove,bracesfortheblockofcodeassociatedwithaWhileloopcanbeomittedifthecodeconsistsofonlyonestatement,forexample:
i n ta = 1 ; w h i l e ( a<1 0 0 )a=a * 2 ;

Thiswillmerelyincreaseauntilaisnotlessthan100. Whenthecomputerreachestheendofthewhileloop,italwaysgoesbacktothewhilestatementatthetopoftheloop,whereitreevaluatesthecontrollingcondition.Ifthatconditionis"true"atthatinstantevenifitwastemporarily0forafew statementsinsidetheloopthenthecomputerbeginsexecutingthestatementsinsidetheloopagainotherwisethecomputerexitstheloop.Thecomputerdoesnot"continuouslycheck"thecontrollingconditionofawhileloopduringtheexecutionof thatloop.Itonly"peeks"atthecontrollingconditioneachtimeitreachesthe w h i l e atthetopoftheloop. Itisveryimportanttonote,oncethecontrollingconditionofaWhileloopbecomes0(false),theloopwillnotterminateuntiltheblockofcodeisfinishedanditistimetoreevaluatetheconditional.IfyouneedtoterminateaWhileloopimmediatelyupon reachingacertaincondition,considerusing break. Acommonidiomistowrite:


i n ti=5 ; w h i l e ( i ){ p r i n t f ( " j a v aa n dc #c a n ' td ot h i s \ n " ) ; }

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 ; }

C Programming/Print version - Wikibooks, open books for an open world

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

Youwillmostoftenuseloopindexesthatstartfrom0,sincearraysareindexedatzero,butyouwillsometimesuseothervaluestoinitializealoopindexaswell. The increment actioncandootherthings,suchas decrement .Sothiskindofloopiscommon:


f o r( i=5 ;i>0 ;i ){ p r i n t f ( " % d" , i ) ; }

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

C Programming/Print version - Wikibooks, open books for an open world

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 ) ;

Notetheterminatingsemicolon.Thisisrequiredforcorrectsyntax.Sincethisisalsoatypeofwhileloop, breakand continuestatementswithintheloopfunctionaccordingly.A continuestatementcausesajumptothetestoftheconditionanda break statementexitstheloop. ItisworthnotingthatDoWhileandWhilearefunctionallyalmostidentical,withoneimportantdifference:DoWhileloopsarealwaysguaranteedtoexecuteatleastonce,butWhileloopswillnotexecuteatalliftheirconditionis0(false)onthefirst evaluation.

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 ; }

C Programming/Print version - Wikibooks, open books for an open world

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
}

C Programming/Print version - Wikibooks, open books for an open world

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* / }

We'vepreviouslysaidthatafunctioncantakenoarguments,orcanreturnnothing,orboth.Whatdowewriteifwewantthefunctiontoreturnnothing?WeuseC's v o i d keyword. v o i d basicallymeans"nothing"soifwewanttowriteafunctionthatreturns nothing,forexample,wewrite


v o i ds a y h e l l o ( i n tn u m b e r _ o f _ t i m e s ) { i n ti ; f o r ( i = 1 ;i< =n u m b e r _ o f _ t i m e s ;i + + ){

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 ' ' ' " ) ; } }

C Programming/Print version - Wikibooks, open books for an open world

Noticethatthereisno r e t u r n statementinthefunctionabove.Sincethere'snone,wewrite v o i d asthereturntype.(Actually,onecanusethe r e t u r n keywordinaproceduretoreturntothecallerbeforetheendoftheprocedure,butonecannotreturna valueasifitwereafunction.) Whataboutafunctionthattakesnoarguments?Ifwewanttodothis,wecanwriteforexample


f l o a tc a l c u l a t e _ n u m b e r ( v o i d ) { f l o a tt o _ r e t u r n = 1 ; i n ti ; f o r ( i = 0 ;i<1 0 0 ;i + + ){ t o _ r e t u r n+ =1 ; t o _ r e t u r n=1 / t o _ r e t u r n ; } r e t u r nt o _ r e t u r 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 ) ;

C Programming/Print version - Wikibooks, open books for an open world

Ifafunctiondoesn'treturnanything,wecanjustsay
s a y _ h e l l o ( ) ;

sincewedon'tneedavariabletocatchitsreturnvalue.

FunctionsfromtheCStandardLibrary
WhiletheClanguagedoesn'titselfcontainfunctions,itisusuallylinkedwiththeCStandardLibrary.Tousethislibrary,youneedtoaddan#includedirectiveatthetopoftheCfile,whichmaybeoneofthefollowing:

< 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 > < s t d d e f . h > < s t d i o . h >

< s t d l i b . h > < s t r i n g . h >

< 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 >

isalnum,isalpha,isblank iscntrl,isdigit,isgraph islower,isprint,ispunct isspace,isupper,isxdigit tolower,toupper

structlconv*localeconv(void) char*setlocale(int,constchar*)

va_start(va_list,ap) va_arg(ap,(type)) va_end(ap) va_copy(va_list,va_list)

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

math.h sin,cos,tan asin,acos,atan,atan2 sinh,cosh,tanh ceil exp

stddef.h

asctime(structtm*tmptr) clock_tclock() char*ctime(consttime_t*timer)

en.wikibooks.org/wiki/C_Programming/Print_version

43/118

10/24/13
fabs floor fmod frexp ldexp log,log10 modf pow sqrt

C Programming/Print version - Wikibooks, open books for an open world


doubledifftime(time_ttimer2,time_ttimer1) structtm*gmtime(consttime_t*timer) structtm*gmtime_r(consttime_t*timer,structtm*result) structtm*localtime(consttime_t*timer) time_tmktime(structtm*ptm) time_ttime(time_t*timer) char*strptime(constchar*buf,constchar*format,structtm*tptr) time_ttimegm(structtm*brokentime)

(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 ,. . . ) ;

Notethatbecauseofthewayvariablelengthargumentswork,wemustsomehow,inthearguments,specifythenumberofelementsinthevariablelengthpartofthearguments.Inthe a v e r a g e functionhere,it'sdonethroughanargumentcalled n _ a r g s . In the p r i n t f function,it'sdonewiththeformatcodesthatyouspecifyinthatfirststringintheargumentsyouprovide. Nowthatthefunctionhasbeendeclaredasusingvariablelengtharguments,wemustnextwritethecodethatdoestheactualworkinthefunction.Toaccessthenumbersstoredinthevariablelengthargumentlistforour a v e r a g e function,wemustfirst declareavariableforthelistitself:


v a _ l i s tm y L i s t ;

The v a _ l i s t typeisatypedeclaredinthe s t d a r g . h headerthatbasicallyallowsyoutokeeptrackofyourlist.Tostartactuallyusing m y L i s t ,however,wemustfirstassignitavalue.Afterall,simplydeclaringitbyitselfwouldn'tdoanything.Todothis,we mustcall v a _ s t a r t ,whichisactuallyamacrodefinedin s t d a r g . h . Intheargumentsto v a _ s t a r t ,youmustprovidethe v a _ l i s t variableyouplanonusing,aswellasthenameofthelastvariableappearingbeforetheellipsisinyourfunctiondeclaration:


# 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 ) ; v a _ e n d( m y L i s t ) ;

en.wikibooks.org/wiki/C_Programming/Print_version

44/118

10/24/13
}

C Programming/Print version - Wikibooks, open books for an open world

Nowthat m y L i s t hasbeenpreppedforusage,wecanfinallystartaccessingthevariablesstoredinit.Todoso,usethe v a _ a r g macro,whichpopsoffthenextargumentonthelist.Intheargumentsto v a _ a r g ,providethe v a _ l i s t variableyou'reusing,aswell astheprimitivedatatype(e.g. i n t , c h a r )thatthevariableyou'reaccessingshouldbe:


# 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 tm y N u m b e r=v a _ a r g( m y L i s t ,i n t ) ; v a _ e n d( m y L i s t ) ; }

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 ; }

Bycalling a v e r a g e( 2 ,1 0 ,2 0 ) ,wegettheaverageof 1 0 and 2 0 ,whichis 1 5 .

Preprocessor
PreprocessorsareawayofmakingtextprocessingwithyourCprogrambeforetheyareactuallycompiled.BeforetheactualcompilationofeveryCprogramitispassedthroughaPreprocessor.ThePreprocessorlooksthroughtheprogramtryingtofind outspecificinstructionscalledPreprocessordirectivesthatitcanunderstand.AllPreprocessordirectivesbeginwiththe#(hash)symbol.C++compilersusethesameCpreprocessor. [5] Thepreprocessorisapartofthecompilerwhichperformspreliminaryoperations(conditionallycompilingcode,includingfilesetc...)toyourcodebeforethecompilerseesit.Thesetransformationsarelexical,meaningthattheoutputofthepreprocessoris stilltext.

NOTE:TechnicallytheoutputofthepreprocessingphaseforCconsistsofasequenceoftokens,ratherthansourcetext,butitissimpletooutputsourcetextwhichisequivalenttothegiventokensequence,andthatiscommonly supportedbycompilersviaa E or / E optionalthoughcommandlineoptionstoCcompilersaren'tcompletelystandard,manyfollowsimilarrules.

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

C Programming/Print version - Wikibooks, open books for an open world

Ifusinganglebracketsliketheexampleabove,thepreprocessorisinstructedtosearchfortheincludefilealongthedevelopmentenvironmentpathforthestandardincludes.
# i n c l u d e" o t h e r . h "

Ifyouusequotationmarks("" ),thepreprocessorisexpectedtosearchinsomeadditional,usuallyuserdefined,locationsfortheheaderfile,andtofallbacktothestandardincludepathsonlyifitisnotfoundinthoseadditionallocations.Itiscommonfor thisformtoincludesearchinginthesamedirectoryasthefilecontainingthe # i n c l u d e directive.

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 >

< s t d d e f . h > < s t d i o . h > < s t d l i b . h > < s t r i n g . h >

HeadersaddedsinceC90:

< c o m p l e x . h > < f e n v . h > < i n t t y p e s . h >

< i s o 6 4 6 . h > < s t d b o o l . h > < s t d i n t . h >

< t g m a t h . h > < w c h a r . h > < w c t y p e . h >

#pragma
The pragma(pragmaticinformation)directiveispartofthestandard,butthemeaningofanypragmadependsonthesoftwareimplementationofthestandardthatisused.The#pragmadirectiveprovidesawaytorequestspecialbehaviorfromthe compiler.Thisdirectiveismostusefulforprogramsthatareunusuallylargeorthatneedtotakeadvantageofthecapabilitiesofaparticularcompiler. Pragmasareusedwithinthesourceprogram.
# p r a g m at o k e n ( s )

1. pragmaisusuallyfollowedbyasingletoken,whichrepresentsacommandforthecompilertoobey.YoushouldcheckthesoftwareimplementationoftheCstandardyouintendonusingforalistofthesupportedtokens.Notsurprisingly,thesetof commandsthatcanappearin#pragmadirectivesisdifferentforeachcompileryou'llhavetoconsultthedocumentationforyourcompilertoseewhichcommandsitallowsandwhatthosecommandsdo. Forinstanceoneofthemostimplementedpreprocessordirectives, # p r a g m ao n c e whenplacedatthebeginningofaheaderfile,indicatesthatthefilewhereitresideswillbeskippedifincludedseveraltimesbythepreprocessor.

NOTE:Othermethodsexisttodothisactionthatiscommonlyreferredasusing includeguards.

# d e f i n e

WARNING:Preprocessormacros,althoughtempting,canproducequiteunexpectedresultsifnotdoneright.Alwayskeepinmindthatmacrosaretextualsubstitutionsdonetoyoursourcecodebeforeanythingiscompiled.Thecompiler doesnotknowanythingaboutthemacrosandnevergetstoseethem.Thiscanproduceobscureerrors,amongstothernegativeeffects.Prefertouselanguagefeatures,ifthereareequivalent(Inexampleuse c o n s ti n t or e n u m insteadof # d e f i n e dconstants). Thatsaid,therearecases,wheremacrosareveryuseful(seethe d e b u g macrobelowforanexample).

en.wikibooks.org/wiki/C_Programming/Print_version

46/118

10/24/13

C Programming/Print version - Wikibooks, open books for an open world

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)){ . . . }

It'sgenerallyagoodideatouseextraparentheseswhenusingcomplexmacros.Noticethatintheaboveexample,thevariable"x"isalwayswithinitsownsetofparentheses.Thisway,itwillbeevaluatedinwhole,beforebeingcomparedto0or multipliedby1.Also,theentiremacroissurroundedbyparentheses,topreventitfrombeingcontaminatedbyothercode.Ifyou'renotcareful,youruntheriskofhavingthecompilermisinterpretyourcode. Becauseofsideeffectsitisconsideredaverybadideatousemacrofunctionsasdescribedabove.


i n tx=1 0 ; i n ty=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 ;

Thus,afterexecution i = 8 and j = 3 insteadoftheexpectedresultof i = j = 8 !Thisiswhyyouwerecautionedtouseanextrasetofparenthesisabove,butevenwiththese,theroadisfraughtwithdangers.Thealertreadermightquicklyrealize thatif a or b containsexpressions,thedefinitionmustparenthesizeeveryuseof a , b inthemacrodefinition,likethis:


# d e f i n eM A X ( a , b )( ( a ) > ( b ) ? ( a ) : ( b ) )

Thisworks,provided a , b havenosideeffects.Indeed,
i=2 ; j=3 ; k=M A X ( i + + ,j + + ) ;

wouldresultin k = 4 , i = 3 and j = 5 .Thiswouldbehighlysurprisingtoanyoneexpecting M A X ( ) tobehavelikeafunction. Sowhatisthecorrectsolution?Thesolutionisnottousemacroatall.Aglobal,inlinefunction,likethis


i n l i n ei n tm a x ( i n ta ,i n tb ){ r e t u r na > b ? a : b }

hasnoneofthepitfallsabove,butwillnotworkwithalltypes.

en.wikibooks.org/wiki/C_Programming/Print_version

47/118

10/24/13

C Programming/Print version - Wikibooks, open books for an open world

NOTE:Theexplicit i n l i n e declarationisnotreallynecessaryunlessthedefinitionisinaheaderfile,sinceyourcompilercaninlinefunctionsforyou(withgccthiscanbedonewith f i n l i n e f u n c t i o n s or O 3 ).Thecompileris oftenbetterthantheprogrammeratpredictingwhichfunctionsareworthinlining.Also,functioncallsarenotreallyexpensive(theyusedtobe). Thecompilerisactuallyfreetoignorethe i n l i n e keyword.Itisonlyahint(exceptthat i n l i n e isnecessaryinordertoallowafunctiontobedefinedinaheaderfilewithoutgeneratinganerrormessageduetothefunction beingdefinedinmorethanonetranslationunit).

(#,##) The #and ##operatorsareusedwiththe # d e f i n e macro.Using#causesthefirstargumentafterthe #tobereturnedasastringinquotes.Forexample,thecommand


# d e f i n ea s _ s t r i n g (s)#s

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 ! ") ;

Using ##concatenateswhat'sbeforethe ##withwhat'safterit.Forexample,thecommand


# d e f i n ec o n c a t e n a t e (x ,y)x# #y . . . i n tx y=1 0 ; . . .

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 ) ;

whichwill,ofcourse,display 1 0 tostandardoutput. Itispossibletoconcatenateamacroargumentwithaconstantprefixorsuffixtoobtainavalididentifierasin


# d e f i n em a k e _ f u n c t i o n (n a m e)i n tm y _# #n a m e( i n tf o o ){ } m a k e _ f u n c t i o n (b a r)

whichwilldefineafunctioncalled m y _ b a r ( ) .Butitisn'tpossibletointegrateamacroargumentintoaconstantstringusingtheconcatenationoperator.Inordertoobtainsuchaneffect,onecanusetheANSICpropertythattwoormoreconsecutivestring constantsareconsideredequivalenttoasinglestringconstantwhenencountered.Usingthisproperty,onecanwrite


# d e f i n ee a t (w h a t)p u t s (" I ' me a t i n g"# w h a t"t o d a y . ") e a t (f r u i t)

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 ) ) ;

C Programming/Print version - Wikibooks, open books for an open world

Thisisabittricky,sinceitisexpandedin2steps.First n u m 2 s t r ( C O N S T ) isreplacedwith s t r ( 2 3 ) ,whichinturnisreplacedwith " 2 3 " .Thiscanbeusefulinthefollowingexample:


# i f d e fD E B U G # d e f i n ed e b u g ( m s g )f p u t s ( _ _ F I L E _ _" : "n u m 2 s t r ( _ _ L I N E _ _ )"-"m s g ,s t d e r r ) # e l s e # d e f i n ed e b u g ( m s g ) # e n d i f

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")

NOTE: Itisusuallybadpracticetodefinemacrosinheaders. Amacroshouldbedefinedonlywhenitisnotpossibletoachievethesameresultwithafunctionorsomeothermechanism.Somecompilersareabletooptimizecodetowherecallstosmallfunctionsarereplacedwithinlinecode, negatinganypossiblespeedadvantage.Usingtypedefs,enums,and i n l i n e (inC99)isoftenabetteroption.

Oneofthefewsituationswhereinlinefunctionswon'tworksoyouareprettymuchforcedtousefunctionlikemacrosinsteadistoinitializecompiletimeconstants(staticinitializationofstructs).Thishappenswhentheargumentstothemacroare literalsthatthecompilercanoptimizetoanotherliteral. [6]

#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

C Programming/Print version - Wikibooks, open books for an open world

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

TheconditionalexpressioncouldcontainanyCoperatorexceptfortheassignmentoperators,theincrementanddecrementoperators,theaddressofoperator,andthesizeofoperator. Oneuniqueoperatorusedinpreprocessingandnowhereelseisthe definedoperator.Itreturns1ifthemacroname,optionallyenclosedinparentheses,iscurrentlydefined0ifnot. The #endifcommandendsablockstartedby # i f , # i f d e f ,or # i f n d e f . The #elifcommandissimilarto # i f ,exceptthatitisusedtoextractonefromaseriesofblocksofcode.E.g.:


# i f/ *s o m ee x p r e s s i o n* / : : : # e l i f/ *a n o t h e re x p r e s s i o n* / : / *i m a g i n em a n ym o r e# e l i f sh e r e. . .* / : # e l s e / *T h eo p t i o n a l# e l s eb l o c ki ss e l e c t e di fn o n eo ft h ep r e v i o u s# i fo r # e l i fb l o c k sa r es e l e c t e d* / : : # e n d i f/ *T h ee n do ft h e# i fb l o c k* /

#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

The #ifndefcommandissimilarto #ifdef,exceptthatthetestisreversed:


# i f n d e fN 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

C Programming/Print version - Wikibooks, open books for an open world

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 . . . )

ThemostcommonusageofXMacrosistoestablishalistofCobjectsandthenautomaticallygeneratecodeforeachofthem.Someimplementationsalsoperformany # u n d e f stheyneedinsidetheXMacro,asopposedtoexpectingthecallertoundefine them. Commonsetsofobjectsareasetofglobalconfigurationsettings,asetofmembersofastruct,alistofpossibleXMLtagsforconvertinganXMLfiletoaquicklytraversabletree,orthebodyofanenumdeclarationotherlistsarepossible. OncetheXMacrohasbeenprocessedtocreatethelistofobjects,thecomponentmacroscanberedefinedtogenerate,forinstance,accessorand/ormutatorfunctions.Structureserializinganddeserializingarealsocommonlydone. HereisanexampleofanXMacrothatestablishesastructandautomaticallycreatesserialize/deserializefunctions.Forsimplicity,thisexampledoesn'taccountforendiannessorbufferoverflows. File star.def:


E X P A N D _ E X P A N D _ S T A R _ M E M B E R ( x ,i n t ) E X P A N D _ E X P A N D _ S T A R _ M E M B E R ( y ,i n t ) E X P A N D _ E X P A N D _ S T A R _ M E M B E R ( z ,i n t ) E X P A N D _ E X P A N D _ S T A R _ M E M B E R ( r a d i u s ,d o u b l e ) # u n d e fE X P A N D _ E X P A N D _ S T A R _ M E M B E R

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 " }

Handlersforindividualdatatypesmaybecreatedandaccessedusingtokenconcatenation(" # # ")andquoting(" # ")operators.Forexample,thefollowingmightbeaddedtotheabovecode:


# 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 _ 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 :" ,# 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 " ) ;

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 " }

C Programming/Print version - Wikibooks, open books for an open world

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 " }

Thecreationofaseparateheaderfilecanbeavoidedbycreatingasinglemacrocontainingwhatwouldbethecontentsofthefile.Forinstance,theabovefile"star.def"couldbereplacedwiththismacroatthebeginningof: File star_table.c:


# d e f i n eE X P A N D _ S T A R\ E X P A N D _ S T A R _ M E M B E R ( x ,i n t )\ E X P A N D _ S T A R _ M E M B E R ( y ,i n t )\ E X P A N D _ S T A R _ M E M B E R ( z ,i n t )\ E X P A N D _ S T A R _ M E M B E R ( r a d i u s ,d o u b l e )

andthenallcallsto # i n c l u d e" s t a r . d e f " couldbereplacedwithasimple E X P A N D _ S T A R statement.Therestoftheabovefilewouldbecome:


t y p e d e fs t r u c t{ # 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 )t y p em e m b e r ; E X P A N D _ S T A R # u n d e f E X P A N D _ S T A R _ M E M B E R }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 _ 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 ) ; E X P A N D _ S T A R # u n d e f E X P A N D _ S T A R _ M E M B E R } 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 _ 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 ) ; E X P A N D _ S T A R # u n d e f E X P A N D _ S T A R _ M E M B E R }

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
}

C Programming/Print version - Wikibooks, open books for an open world

Avariantwhichavoidsneedingtoknowthemembersofanyexpandedsubmacrosistoaccepttheoperatorsasanargumenttothelistmacro: File star_table.c:


/ * G e n e r i c * / # d e f i n eS T R U C T _ M E M B E R ( m e m b e r ,t y p e ,d u m m y )t y p em e m b e r ; # d e f i n eS E R I A L I Z E _ M E M B E R ( m e m b e r ,t y p e ,o b j ,b u f f e r )\ m e m c p y ( b u f f e r ,& ( o b j > m e m b e r ) ,s i z e o f ( o b j > m e m b e r ) ) ;\ b u f f e r+ =s i z e o f ( o b j > m e m b e r ) ; # d e f i n eD E S E R I A L I Z E _ M E M B E R ( m e m b e r ,t y p e ,o b j ,b u f f e r )\ m e m c p y ( & ( o b j > m e m b e r ) ,b u f f e r ,s i z e o f ( o b j > m e m b e r ) ) ;\ b u f f e r+ =s i z e o f ( o b j > m e m b e r ) ; # 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 " / *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 eP R I N T _ M E M B E R ( m e m b e r ,t y p e ,o b j )\ p r i n t f ( " % s :"F O R M A T _ ( t y p e )" \ n " ,# m e m b e r ,o b j > m e m b e r ) ; / * s t a r S t r u c t * / # d e f i n eE X P A N D _ S T A R ( _ ,. . . )\ _ ( x ,i n t ,_ _ V A _ A R G S _ _ )\ _ ( y ,i n t ,_ _ V A _ A R G S _ _ )\ _ ( z ,i n t ,_ _ V A _ A R G S _ _ )\ _ ( r a d i u s ,d o u b l e ,_ _ V A _ A R G S _ _ ) t y p e d e fs t r u c t{ E X P A N D _ S T A R ( S T R U C T _ M E M B E R ,) }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 ){ E X P A N D _ S T A R ( S E R I A L I Z E _ M E M B E R ,s t a r ,b u f f e r ) } 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 ){ E X P A N D _ S T A R ( D E S E R I A L I Z E _ M E M B E R ,s t a r ,b u f f e r ) } 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 ){ E X P A N D _ S T A R ( P R I N T _ M E M B E R ,s t a r ) }

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

C Programming/Print version - Wikibooks, open books for an open world

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* /

C Programming/Print version - Wikibooks, open books for an open world

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

C Programming/Print version - Wikibooks, open books for an open world

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

C Programming/Print version - Wikibooks, open books for an open world

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 .* /

C Programming/Print version - Wikibooks, open books for an open world

Bydefault s t d i n pointstothekeyboardand s t d o u t and s t d e r r pointtothescreen.ItispossibleunderUnixandmaybepossibleunderotheroperatingsystemstoredirectinputfromoroutputtoafileorboth.

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

cleared,andiftheopenoperationfailserrorisset. f r e o p e n differsfrom f o p e n inthatthefilepointedtoby s t r e a m isclosedfirstwhenalreadyopenandanycloseerrorsareignored.


m o d e forbothfunctionspointstoastringconsistingofoneofthefollowingsequences:

r w a r b w b a b r + w + a + r + bo rr b + w + bo rw b + a + bo ra b +

o p e nat e x tf i l ef o rr e a d i n g t r u n c a t et oz e r ol e n g t ho rc r e a t eat e x tf i l ef o rw r i t i n g a p p e n d ;o p e no rc r e a t et e x tf i l ef o rw r i t i n ga te n d o f f i l e o p e nb i n a r yf i l ef o rr e a d i n g t r u n c a t et oz e r ol e n g t ho rc r e a t eab i n a r yf i l ef o rw r i t i n g a p p e n d ;o p e no rc r e a t eb i n a r yf i l ef o rw r i t i n ga te n d o f f i l e o p e nt e x tf i l ef o ru p d a t e( r e a d i n ga n dw r i t i n g ) t r u n c a t et oz e r ol e n g t ho rc r e a t eat e x tf i l ef o ru p d a t e a p p e n d ;o p e no rc r e a t et e x tf i l ef o ru p d a t e o p e nb i n a r yf i l ef o ru p d a t e( r e a d i n ga n dw r i t i n g ) t r u n c a t et oz e r ol e n g t ho rc r e a t eab i n a r yf i l ef o ru p d a t e a p p e n d ;o p e no rc r e a t eb i n a r yf i l ef o ru p d a t e

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 ) ;

The f c l o s e functioncausesthestreampointedtoby s t r e a m tobeflushedandtheassociatedfiletobeclosed.Anyunwrittenbuffereddataforthestreamaredeliveredtothehostenvironmenttobewrittentothefileanyunreadbuffereddataarediscarded. Thestreamisdisassociatedfromthefile.Iftheassociatedbufferwasautomaticallyallocated,itisdeallocated.Thefunctionreturnszeroifthestreamwassuccessfullyclosedor E O F ifanyerrorsweredetected.

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

C Programming/Print version - Wikibooks, open books for an open world

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 ) ;

Exceptthatitreturnsnovalue,the s e t b u f functionisequivalenttothe s e t v b u f functioninvokedwiththevalues _ I O F B F for m o d e and B U F S I Z for s i z e ,or(if b u f isanullpointer)withthevalue _ I O N B F for m o d e .

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 .

Thef g e t p o s andf s e t p o s functions


# i n c l u d e< s t d i o . h > i n tf g e t p o s ( F I L E* s t r e a m ,f p o s _ t* p o s ) ; i n tf s e t p o s ( F I L E* s t r e a m ,c o n s tf p o s _ 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 .

Thef s e e k andf t e l l functions


# i n c l u d e< s t d i o . h > i n tf s e e k ( F I L E* s t r e a m ,l o n gi n to f f s e t ,i n tw h e n c e ) ; l o n gi n tf t e l l ( F I L E* s t r e a m ) ;

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

C Programming/Print version - Wikibooks, open books for an open world

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 ) ;

The r e w i n d functionsetsthefilepositionindicatorforthestreampointedtoby s t r e a m tothebeginningofthefile.Itisequivalentto


( v o i d ) f s e e k ( s t r e a m ,0 L ,S E E K _ S E T )

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 ) ;

The f e o f functionteststheendoffileindicatorforthestreampointedtoby s t r e a m andreturnsnonzeroifandonlyiftheendoffileindicatorissetfor s t r e a m ,otherwiseitreturnszero.

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 ) ;

The f e r r o r functionteststheerrorindicatorforthestreampointedtoby s t r e a m andreturnsnonzeroifandonlyiftheerrorindicatorissetfor s t r e a m ,otherwiseitreturnszero.

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 ) ;

The r e m o v e functioncausesthefilewhosenameisthestringpointedtoby f i l e n a m e tobenolongeraccessiblebythatname.Asubsequentattempttoopenthatfileusingthatnamewillfail,unlessitiscreatedanew.Ifthefileisopen,thebehaviorofthe r e m o v e functionisimplementationdefined. The r e m o v e functionreturnszeroiftheoperationsucceeds,nonzeroifitfails.

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 ) ;

C Programming/Print version - Wikibooks, open books for an open world

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 ) ;

The t m p f i l e functioncreatesatemporarybinaryfilethatwillautomaticallyberemovedwhenitisclosedoratprogramtermination.Iftheprogramterminatesabnormally,whetheranopentemporaryfileisremovedisimplementationdefined.Thefileis openedforupdatewith " w b + " mode. The t m p f i l e functionreturnsapointertothestreamofthefilethatitcreated.Ifthefilecannotbecreated,the t m p f i l e functionreturnsanullpointer.

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 .* /

C Programming/Print version - Wikibooks, open books for an open world

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

C Programming/Print version - Wikibooks, open books for an open world

Asuccessfulcalltothe u n g e t c functionclearstheendoffileindicatorforthestream.Thevalueofthefilepositionindicatorforthestreamafterreadingordiscardingallpushedbackcharactersshallbethesameasitwasbeforethecharacterswerepushed back.Foratextstream,thevalueofitsfilepositionindicatorafterasuccessfulcalltothe u n g e t c functionisunspecifieduntilallpushedbackcharactersarereadordiscarded.Forabinarystream,itsfilepositionindicatorisdecrementedbyeachsuccessful calltothe u n g e t c functionifitsvaluewaszerobeforeacall,itisindeterminateafterthecall. The u n g e t c functionreturnsthecharacterpushedbackafterconversion,or E O F iftheoperationfails.

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.

The f s c a n f functionexecuteseachdirectiveoftheformatinturn.Ifadirectivefails,asdetailedbelow,the f s c a n f functionreturns.Failuresaredescribedasinputfailures(duetotheunavailabilityofinputcharacters)ormatchingfailures(duetoinappropriate

en.wikibooks.org/wiki/C_Programming/Print_version

63/118

10/24/13

C Programming/Print version - Wikibooks, open books for an open world

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

Matchesanoptionallysigneddecimalinteger,whoseformatisthesameasexpectedforthesubjectsequenceofthe s t r t o l functionwiththevalue10forthe b a s e argument.Thecorrespondingargumentshallbeapointertointeger.


i

Matchesanoptionallysignedinteger,whoseformatisthesameasexpectedforthesubjectsequenceofthe s t r t o l functionwiththevalue0forthe b a s e argument.Thecorrespondingargumentshallbeapointertointeger.


o

Matchesanoptionallysignedoctalinteger,whoseformatisthesameasexpectedforthesubjectsequenceofthe s t r t o u l functionwiththevalue8forthe b a s e argument.Thecorrespondingargumentshallbeapointertounsignedinteger.


u

Matchesanoptionallysigneddecimalinteger,whoseformatisthesameasexpectedforthesubjectsequenceofthe s t r t o u l functionwiththevalue10forthe b a s e argument.Thecorrespondingargumentshallbeapointertounsignedinteger.


x

Matchesanoptionallysignedhexadecimalinteger,whoseformatisthesameasexpectedforthesubjectsequenceofthe s t r t o u l functionwiththevalue16forthe b a s e argument.Thecorrespondingargumentshallbeapointertounsignedinteger.


e , f , g

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

Matchesanimplementationdefinedsetofsequences,whichshouldbethesameasthesetofsequencesthatmaybeproducedbythe % p conversionofthe f p r i n t f function.Thecorrespondingargumentshallbeapointerto v o i d .Theinterpretation oftheinputthenisimplementationdefined.Iftheinputitemisavalueconvertedearlierduringthesameprogramexecution,thepointerthatresultsshallcompareequaltothatvalueotherwisethebehaviorofthe % p conversionisundefined.


n

Noinputisconsumed.Thecorrespondingargumentshallbeapointertointegerintowhichistobewrittenthenumberofcharactersreadfromtheinputstreamsofarbythiscalltothe f s c a n f function.Executionofa % n directivedoesnotincrement theassignmentcountreturnedatthecompletionofexecutionofthe f s c a n f function.


%

Matchesasingle % noconversionorassignmentoccurs.Thecompleteconversionspecificationshallbe % % .

en.wikibooks.org/wiki/C_Programming/Print_version

64/118

10/24/13
Ifaconversionspecificationisinvalid,thebehaviorisundefined.

C Programming/Print version - Wikibooks, open books for an open world

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 ) ;

The f p u t c functionwritesthecharacterspecifiedby c (convertedtoan u n s i g n e dc h a r )tothestreampointedtoby s t r e a m atthepositionindicatedbytheassociatedfilepositionindicator(ifdefined),andadvancestheindicatorappropriately.Ifthefilecannot supportpositioningrequests,orifthestreamisopenedwithappendmode,thecharacterisappendedtotheoutputstream.Thefunctionreturnsthecharacterwritten,unlessawriteerroroccurs,inwhichcasetheerrorindicatorforthestreamissetand f p u t c returns E O F . The f p u t s function

# 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 ) ;

The f p u t s functionwritesthestringpointedtoby s tothestreampointedtoby s t r e a m .Theterminatingnullcharacterisnotwritten.Thefunctionreturns E O F ifawriteerroroccurs,otherwiseitreturnsanonnegativevalue. The p u t c function

# 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 ) ;

The p u t c functionisequivalentto f p u t c ,exceptthatifitisimplementedasamacro,itmayevaluate s t r e a m morethanonce,sotheargumentshouldneverbeanexpressionwithsideeffects.Thefunctionreturnsthecharacterwritten,unlessawriteerror occurs,inwhichcasetheerrorindicatorforthestreamissetandthefunctionreturns E O F . The p u t c h a r function

# 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 ) ;

The p u t c h a r functionisequivalentto p u t c withthesecondargument s t d o u t .Itreturnsthecharacterwritten,unlessawriteerroroccurs,inwhichcasetheerrorindicatorfor s t d o u t issetandthefunctionreturns E O F . The p u t s function

# 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 ) ;

The p u t s functionwritesthestringpointedtoby s tothestreampointedtoby s t d o u t ,andappendsanewlinecharactertotheoutput.Theterminatingnullcharacterisnotwritten.Thefunctionreturns E O F ifawriteerroroccursotherwise,itreturnsa nonnegativevalue.

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 ) ;

C Programming/Print version - Wikibooks, open books for an open world

The f w r i t e functionwrites,fromthearraypointedtoby p t r ,upto n m e m b elementswhosesizeisspecifiedby s i z e tothestreampointedtoby s t r e a m .Thefilepositionindicatorforthestream(ifdefined)isadvancedbythenumberofcharacterssuccessfully written.Ifanerroroccurs,theresultingvalueofthefilepositionindicatorforthestreamisindeterminate.Thefunctionreturnsthenumberofelementssuccessfullywritten,whichwillbelessthan n m e m b onlyifawriteerrorisencountered.

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.)
+

Theresultofasignedconversionalwaysbeginswithaplusorminussign.(Itbeginswithasignonlywhenanegativevalueisconvertedifthisflagisnotspecified.Theresultsofallfloatingconversionsofanegativezero,andofnegativevalues thatroundtozero,includeaminussign.) space Ifthefirstcharacterofasignedconversionisnotasign,orifasignedconversionresultsinnocharacters,aspaceisprefixedtotheresult.Ifthespaceand + flagsbothappear,thespaceflagisignored.


#

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

For d , i , o , u , x , X , a , A , e , E , f , F , g ,and G conversions,leadingzeros(followinganyindicationofsignorbase)areusedtopadtothefieldwidthnospacepaddingisperformed.Ifthe 0 and flagsbothappear,the 0 flagisignored.For d , i , o , u , x ,and


X conversions,ifaprecisionisspecified,the 0 flagisignored.Forotherconversions,thebehaviorisundefined.

Thelengthmodifiersandtheirmeaningsare:
h h

(C99)Specifiesthatafollowing d , i , o , u , x ,or X conversionspecifierappliestoa s i g n e dc h a r or u n s i g n e dc h a r argument(theargumentwillhavebeenpromotedaccordingtotheintegerpromotions,butitsvalueshallbeconvertedto s i g n e dc h a r or u n s i g n e d


c h a r beforeprinting)orthatafollowing n conversionspecifierappliestoapointertoa s i g n e dc h a r argument. h

en.wikibooks.org/wiki/C_Programming/Print_version

66/118

10/24/13

C Programming/Print version - Wikibooks, open books for an open world

Specifiesthatafollowing d , i , o , u , x ,or X conversionspecifierappliestoa s h o r ti n t or u n s i g n e ds h o r ti n t argument(theargumentwillhavebeenpromotedaccordingtotheintegerpromotions,butitsvalueshallbeconvertedto s h o r ti n t or u n s i g n e ds h o r t


i n t beforeprinting)orthatafollowing n conversionspecifierappliestoapointertoa s h o r ti n t argument. l (ell)

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)

(C99)Specifiesthatafollowing d , i , o , u , x ,or X conversionspecifierappliestoa l o n gl o n gi n t or u n s i g n e dl o n gl o n gi n t argumentorthatafollowing n conversionspecifierappliestoapointertoa l o n gl o n gi n t argument.


j

(C99)Specifiesthatafollowing d , i , o , u , x ,or X conversionspecifierappliestoan i n t m a x _ t or u i n t m a x _ t argumentorthatafollowing n conversionspecifierappliestoapointertoan i n t m a x _ t argument.


z

(C99)Specifiesthatafollowing d , i , o , u , x ,or X conversionspecifierappliestoa s i z e _ t orthecorrespondingsignedintegertypeargumentorthatafollowing n conversionspecifierappliestoapointertoasignedintegertypecorrespondingto s i z e _ t argument.


t

(C99)Specifiesthatafollowing d , i , o , u , x ,or X conversionspecifierappliestoa p t r d i f f _ t orthecorrespondingunsignedintegertypeargumentorthatafollowing n conversionspecifierappliestoapointertoa p t r d i f f _ t argument.


L

Specifiesthatafollowing a , A , e , E , f , F , g ,or G conversionspecifierappliestoa l o n gd o u b l e argument. Ifalengthmodifierappearswithanyconversionspecifierotherthanasspecifiedabove,thebehaviorisundefined. Theconversionspecifiersandtheirmeaningsare:


d , i

The i n t argumentisconvertedtosigneddecimalinthestyle [ ]dddd.Theprecisionspecifiestheminimumnumberofdigitstoappearifthevaluebeingconvertedcanberepresentedinfewerdigits,itisexpandedwithleadingzeros.Thedefault precisionis1.Theresultofconvertingazerovaluewithaprecisionofzeroisnocharacters.


o , u , x , X

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

C Programming/Print version - Wikibooks, open books for an open world

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,the i n t argumentisconvertedtoan u n s i g n e dc h a r ,andtheresultingcharacteriswritten. (C99)Ifan l lengthmodifierispresent,the w i n t _ t argumentisconvertedasifbyan l s conversionspecificationwithnoprecisionandanargumentthatpointstotheinitialelementofatwoelementarrayof w c h a r _ t ,thefirstelementcontainingthe


w i n t _ t argumenttothe l c conversionspecificationandthesecondanullwidecharacter. s

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

Theargumentshallbeapointertosignedintegerintowhichiswrittenthenumberofcharacterswrittentotheoutputstreamsofarbythiscallto f p r i n t f .Noargumentisconverted,butoneisconsumed.Iftheconversionspecificationincludesany flags,afieldwidth,oraprecision,thebehaviorisundefined.


%

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

C Programming/Print version - Wikibooks, open books for an open world

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)

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?

C Programming/Print version - Wikibooks, open books for an open world

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

C Programming/Print version - Wikibooks, open books for an open world

Solution

s c a n f ( " % f " , & v a r ) ; / / r e a df l o a ti n t ov a r s c a n f ( " % d " , & v a r ) ; / / r e a di n ti n t ov a r s c a n f ( " % l f " ,& v a r ) ; / / r e a dd o u b l ei n t ov a r

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 ; }

2.Writeaprogramthatpromptstheuserforasentence,andprintseachwordonitsownline. Solution Onepossiblesolutioncouldbe:

# 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 ; }

C Programming/Print version - Wikibooks, open books for an open world

Loops
1.Writeafunctionthatoutputsarightisoscelestriangleofheightandwidth n,so n=3wouldlooklike
* * * * * *

Solution Onepossiblesolution:

v o i di s o s c e l e 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 ' ) ; } }

2.Writeafunctionthatoutputsasidewaystriangleofheight 2n1andwidth n,sotheoutputfor n=4wouldbe:


* * * * * * * * * * * * * * * *

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 " ) ; } }

C Programming/Print version - Wikibooks, open books for an open world

3.Writeafunctionthatoutputsarightsideuptriangleofheight nandwidth 2n1theoutputfor n=6wouldbe:


* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Solution Onepossiblesolution:

v o i dr i g h t _ s i d e _ u p ( i n tn ) { i n tx , y ; f o r( y =1 ;y< =n ;y + + ) { f o r( x =0 ;x<n y ;x + + ) p u t c h a r ( '' ) ; f o r( x =( n y ) ;x<( n y ) + ( 2 * y 1 ) ;x + + ) p u t c h a r ( ' * ' ) ; p u t c h a r ( ' \ n ' ) ; } }

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 ; }

C Programming/Print version - Wikibooks, open books for an open world

2.Writeafunctiontodeterminethenumberofprimenumbersbelown. 3.WriteafunctiontofindthesquarerootbyusingNewton'smethod. 4.Writefunctionstoevaluatethetrigonometricfunctions: 5.Trytowritearandomnumbergenerator. 6.Writeafunctiontodeterminetheprimenumberbetween2and100:

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 ]){

C Programming/Print version - Wikibooks, open books for an open world

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

C Programming/Print version - Wikibooks, open books for an open world

en.wikibooks.org/wiki/C_Programming/Print_version

76/118

10/24/13

C Programming/Print version - Wikibooks, open books for an open world

*i ss i m i l i a rt om o s ta s s e m b l yl a n g u a g e s ,t h e r ei sad a t as t a c k( D S )a n d *ac a l ls t a c k( C S )p o i n t e r ,a n de a c hr e c u r s i v ec a l lt om e r g e s o r t *p u s h e st h er e t u r na d d r e s s,w h i c hi st h ep r o g r a ma d d r e s so ft h ei n s t r u c t i o n *a f t e rt h ec a l l,o n t ot h es t a c kp o i n t e dt ob yC Sa n dC Si si n c r e m e n t e d , *a n dt h ea d d r e s so ft h ea r r a ys t a r ta n di n t e g e rw h i c hi st h es u b a r r a yl e n g t h *o n t ot h ed a t as t a c kp o i n t e dt ob yD S ,w h i c hw i l lb ei n c r e m e n t e dt w i c e . * *I ft h en u m b e ro fr e c u r s i v e,a c t i v ec a l l se x c e e dt h ea l l o w a b l es p a c ef o re i t h e rt h ec a l ls t a c k *o rt h ed a t as t a c k ,t h e nt h ep r o g r a mw i l lc r a s h,o rap r o c e s ss p a c ep r o t e c t i o n *v i o l a t i o ni n t e r r u p ts i g n a lw i l lb es e n tb yt h eC P U ,a n dt h ei n t e r r u p tv e c t o r *f o rt h a ts i g n a lw i l lj u m pt h ep r o c e s s o r ' sc u r r e n ti n s t r u c t i o np o i n t e rt ot h e *i n t e r r u p th a n d l i n gr o u t i n e . * /

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

C Programming/Print version - Wikibooks, open books for an open world

5leavesso3,4>*4,3>+0childgreatestasnorightchild>is4>3?no,soexit 4leaves3. 3leaves*. numbersextractedindescendingorder11,10,6,5,4,3.

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

C Programming/Print version - Wikibooks, open books for an open world

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) ; } }

C Programming/Print version - Wikibooks, open books for an open world

/ / / * 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){

C Programming/Print version - Wikibooks, open books for an open world

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 } ;

C Programming/Print version - Wikibooks, open books for an open world

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 ] ;

ArraysinCareindexedstartingat0,asopposedtostartingat1.Thefirstelementofthearrayaboveis p o i n t [ 0 ] .Theindextothelastvalueinthearrayisthearraysizeminusone.Intheexampleabovethesubscriptsrunfrom0through5.Cdoesnot guaranteeboundscheckingonarrayaccesses.Thecompilermaynotcomplainaboutthefollowing(thoughthebestcompilersdo):


c h a ry ; i n tz=9 ; c h a rp o i n t [ 6 ]={1 ,2 ,3 ,4 ,5 ,6} ; / / e x a m p l e so fa c c e s s i n go u t s i d et h ea r r a y .Ac o m p i l ee r r o ri sn o ta l w a y sr a i s e d y=p o i n t [ 1 5 ] ; y=p o i n t [ 4 ] ; y=p o i n t [ z ] ;

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 ]) ; }

Noticeintheaboveexample,thesizeofthearraywasnotexplicitlyspecified.Thecompilerknowstosizeitat5becauseofthefivevaluesintheinitializerlist.Addinganadditionalvaluetothelistwillcauseittobesizedtosix,andbecauseofthesizeof expressioninthe f o r loop,thecodeautomaticallyadjuststothischange.Goodprogrammingpracticeistodeclareavariable size,andstorethenumberofelementsinthearrayinit. size=sizeof(anArray)/sizeof(short) Calsosupportsmultidimensionalarrays(or,rather,arraysofarrays).Thesimplesttypeisatwodimensionalarray.Thiscreatesarectangulararrayeachrowhasthesamenumberofcolumns.Togetachararraywith3rowsand5columnswewriteinC


c h a rt w o _ d [ 3 ] [ 5 ] ;

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

C Programming/Print version - Wikibooks, open books for an open world

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 ' } ;

Inthefirstexample,thestringwillhaveanullcharacterautomaticallyappendedtotheendbythecompilerbyconvention,libraryfunctionsexpectstringstobeterminatedbyanullcharacter.Thelatterdeclarationindicatesindividualelements,andas suchthenullterminatorneedstobeaddedmanually. Stringsdonotalwayshavetobelinkedtoanexplicitvariable.Asyouhaveseenalready,astringofcharacterscanbecreateddirectlyasanunnamedstringthatisuseddirectly(aswiththeprintffunctions.) Tocreateanextralongstring,youwillhavetosplitthestringintomultiplesections,byclosingthefirstsectionwithaquote,andrecommencingthestringonthenextline(alsostartingandendinginaquote):


c h a rs t r i n g [ ]=" T h i si sav e r y ,v e r yl o n g" " s t r i n gt h a tr e q u i r e st w ol i n e s . " ;

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 ;

C Programming/Print version - Wikibooks, open books for an open world

Lines14defineastructure.Line6declaresavariablewhichpointstoan i n t ,andline7declaresavariablewhichpointstosomethingwithstructureMyStruct.Sotodeclareavariableassomethingwhichpointstosometype,ratherthancontainssome type,theasterisk(* )isplacedbeforethevariablename. Inthefollowing,line1declares v a r 1 asapointertoalongand v a r 2 asalongandnotapointertoalong.Inline2, p 3 isdeclaredasapointertoapointertoanint.

a r 1 a r 2 1 .l o n g * v ,v ; 3 2 . i n t * *p ;

Pointertypesareoftenusedasparameterstofunctioncalls.Thefollowingshowshowtodeclareafunctionwhichusesapointerasanargument.SinceCpassesfunctionargumentsbyvalue,inordertoallowafunctiontomodifyavaluefromthecalling routine,apointertothevaluemustbepassed.Pointerstostructuresarealsousedasfunctionargumentsevenwhennothinginthestructwillbemodifiedinthefunction.Thisisdonetoavoidcopyingthecompletecontentsofthestructureontothestack. Moreaboutpointersasfunctionargumentslater.


i n tM y F u n c t i o n (s t r u c tM y S t r u c t* p S t r u c t) ;

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

C Programming/Print version - Wikibooks, open books for an open world

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 .

b b=& a s t r u c t ; ( * b b ) . m _ a N u m b e r=3 ; / *a s s i g n s3t ot h em _ a N u m b e rm e m b e ro fa s t r u c t* / b b > n u m 2=4 4 . 3 ; / *a s s i g n s4 4 . 3t ot h en u m 2m e m b e ro fa s t r u c t * / * p j=b b > m _ a N u m b e r ; / *e q i v a l e n tt od=a s t r u c t . m _ a N u m b e r ; * /

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 ; }

Pointersandarraynamescanprettymuchbeusedinterchangeably.Thereareexceptions.Youcannotassignanewpointervaluetoanarrayname.Thearraynamewillalwayspointtothefirstelementofthearray.Inthefunction K r a z y F u n c t i o n above,you couldhoweverassignanewvaluetoparm1,asitisjustapointertothefirstelementofmyArray.Itisalsovalidforafunctiontoreturnapointertooneofthearrayelementsfromanarraypassedasanargumenttoafunction.Afunctionshouldnever returnapointertoalocalvariable,eventhoughthecompilerwillprobablynotcomplain. Whendeclaringparameterstofunctions,declaringanarrayvariablewithoutasizeisequivalenttodeclaringapointer.Oftenthisisdonetoemphasizethefactthatthepointervariablewillbeusedinamannerequivalenttoanarray.

/ *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 [ ]) ;

C Programming/Print version - Wikibooks, open books for an open world

Nowwe'rereadytodiscusspointerarithmetic.Youcanaddandsubtractintegervaluesto/frompointers.IfmyArrayisdeclaredtobesometypeofarray,theexpression * ( m y A r r a y + j ) ,wherejisaninteger,isequivalentto m y A r r a y [ j ] .Soforinstanceinthe aboveexamplewherewehadtheexpressionsecondArray[i].num2,wecouldhavewrittenthatas * ( s e c o n d A r r a y + i ) . n u m 2 ormoresimply ( s e c o n d A r r a y + i ) > n u m 2 . Notethatforadditionandsubtractionofintegersandpointers,thevalueofthepointerisnotadjustedbytheintegeramount,butisadjustedbytheamountmultipliedbythesize(inbytes)ofthetypetowhichthepointerrefers.Onepointermayalsobe subtractedfromanother,providedtheypointtoelementsofthesamearray(orthepositionjustbeyondtheendofthearray).Ifyouhaveapointerthatpointstoanelementofanarray,theindexoftheelementistheresultwhenthearraynameis subtractedfromthepointer.Here'sanexample.


s t r u c tM y S t r u c ts o m e A r r a y [ 2 0 ] ; s t r u c tM y S t r u c t* p 2 ; i n ti d x ; . / *a r r a yi n i t i a l i z a t i o n. .* / . f o r( p 2=s o m e A r r a y ;p 2<s o m e A r r a y + 2 0 ; + + p 2 ){ i f( p 2 > n u m 2>t e s t V a l u e )b r e a k ; } i d x=p 2-s o m e A r r a y ;

Youmaybewonderinghowpointersandmultidimensionalarraysinteract.Let'slookatthisabitindetail.SupposeAisdeclaredasatwodimensionalarrayoffloats(f l o a tA [ D 1 ] [ D 2 ] ; )andthatpfisdeclaredapointertoafloat.Ifpfisinitializedtopointto A[0][0],then*(pf+1)isequivalenttoA[0][1]and*(pf+D2)isequivalenttoA[1][0].Theelementsofthearrayarestoredinrowmajororder.

f l o a tA [ 6 ] [ 8 ] ; f l o a t* p f ; p f=& A [ 0 ] [ 0 ] ; * ( p f + 1 )=1 . 3 ; / *a s s i g n s1 . 3t oA [ 0 ] [ 1 ]* / * ( p f + 8 )=2 . 3 ; / *a s s i g n s2 . 3t oA [ 1 ] [ 0 ]* /

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 .* /

Wealsonoteheresomethingcuriousaboutarrayindexing.SupposemyArrayisanarrayandidxisanintegervalue.TheexpressionmyArray[idx]isequivalenttoidx[myArray].Thefirstisequivalentto*(myArray+idx),andthesecondisequivalentto* (idx+myArray).Theseturnouttobethesame,sincetheadditioniscommutative. Pointerscanbeusedwithpreincrementorpostdecrement,whichissometimesdonewithinaloop,asinthefollowingexample.Theincrementanddecrementappliestothepointer,nottotheobjecttowhichthepointerrefers.Inotherwords,*pArray++is equivalentto*(pArray++).


l o n g m y A r r a y [ 2 0 ] ; l o n g * p A r r a y ; i n t i ; / *A s s i g nv a l u e st ot h ee n t r i e so fm y A r r a y* / p A r r a y=m y A r r a y ; f o r( i = 0 ;i < 1 0 ;+ + i ){ * p A r r a y + +=5+3 * i+1 2 * i * i ; * p A r r a y + +=6+2 * i+7 * i * i ; }

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 ; }

C Programming/Print version - Wikibooks, open books for an open world

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) ;

C Programming/Print version - Wikibooks, open books for an open world

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 ) ; }

C Programming/Print version - Wikibooks, open books for an open world

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

C Programming/Print version - Wikibooks, open books for an open world

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 ]* / ; }

Notethatthe s i z e o f operatoronlyworksonthingsdefinedearlierinthesamefunction.Thecompilerreplacesitwithsomefixedconstantnumber.Inthiscase,the b u f f e r wasdeclaredasanarrayof10char'searlierinthesamefunction,andthecompiler replaces s i z e o f ( b u f f e r ) withthenumber10atcompiletime(equivalenttoushardcoding10intothecodeinplaceof s i z e o f ( b u f f e r ) ).Theinformationaboutthelengthof b u f f e r isnotactuallystoredanywhereinmemory(unlesswekeeptrackofitseparately) andcannotbeprogrammaticallyobtainedatruntimefromthearray/pointeritself. Oftenafunctionneedstoknowthesizeofanarrayitwasgivenanarraydefinedinsomeotherfunction.Forexample,


/ *b r o k e n . c-d e m o n s t r a t e saf l a w* / # 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 > # 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 ) ) ) i n ts u m (i n ti n p u t _ a r r a y [ ]) { i n ts u m _ s o _ f a r=0 ; i n ti ; f o r (i=0 ;i<N U M _ E L E M ( i n p u t _ a r r a y ) ;i + +)/ /W O N ' TW O R K-i n p u t _ a r r a yw a s n ' td e f i n e di nt h i sf u n c t i o n . { s u m _ s o _ f a r+ =i n p u t _ a r r a y [ i ] ; } ; r e t u r n (s u m _ s o _ f a r) ; }

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 ; }

C Programming/Print version - Wikibooks, open books for an open world

Unfortunately,(inCandC++)thelengthofthearraycannotbeobtainedfromanarraypassedinatruntime,because(asmentionedabove)thesizeofanarrayisnotstoredanywhere.Thecompileralwaysreplacessizeofwithaconstant.Thissum() routineneedstohandlemorethanjustoneconstantlengthofanarray. Therearesomecommonwaystoworkaroundthisfact: Writethefunctiontorequire,foreacharrayparameter,a"length"parameter(whichhastype"size_t").(Typicallyweusesizeofatthepointwherethisfunctioniscalled). Useofaconvention,suchasanullterminatedstringtomarktheendofthearray. Insteadofpassingrawarrays,passastructurethatincludesthelengthofthearray(suchas".length")aswellasthearray(orapointertothefirstelement)similartothe s t r i n g or v e c t o r classesinC++.


/ *f i x e d . c-d e m o n s t r a t e so n ew o r k a r o u n d* / # 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 > # 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 ) ) ) i n ts u m (i n ti n p u t _ a r r a y [ ] ,s i z e _ tl e n g t h) { i n ts u m _ s o _ f a r=0 ; i n ti ; f o r (i=0 ;i<l e n g t h ;i + +) { s u m _ s o _ f a r+ =i n p u t _ a r r a y [ i ] ; } ; r e t u r n (s u m _ s o _ f a r) ; } 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 ,4} ; 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 ,N U M _ E L E M ( l e f t _ a r r a y )) ;/ /w o r k sh e r e ,b e c a u s el e f t _ a r r a yi sd e f i n e di nt h i sf u n c t i o n 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 ,N U M _ E L E M ( r i g h t _ a r r a y )) ;/ /w o r k sh e r e ,b e c a u s er i g h t _ a r r a yi sd e f i n e di nt h i sf u n c t i o n 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 ; }

It'sworthmentioningthatsizeofoperatorhastwovariations: s i z e o f( t y p e ) (forinstance: s i z e o f( i n t ) or s i z e o f( s t r u c ts o m e _ s t r u c t u r e ) )and s i z e o fe x p r e s s i o n (forinstance: s i z e o fs o m e _ v a r i a b l e . s o m e _ f i e l d or s i z e o f1 ).

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

C Programming/Print version - Wikibooks, open books for an open world

TheCfunction m a l l o c isthemeansofimplementingdynamicmemoryallocation.Itisdefinedinstdlib.hormalloc.h,dependingonwhatoperatingsystemyoumaybeusing.Malloc.hcontainsonlythedefinitionsforthememoryallocationfunctionsandnot therestoftheotherfunctionsdefinedinstdlib.h.Usuallyyouwillnotneedtobesospecificinyourprogram,andifbotharesupported,youshoulduse<stdlib.h>,sincethatisANSIC,andwhatwewillusehere. Thecorrespondingcalltoreleaseallocatedmemorybacktotheoperatingsystemis f r e e . Whendynamicallyallocatedmemoryisnolongerneeded, f r e e shouldbecalledtoreleaseitbacktothememorypool.Overwritingapointerthatpointstodynamicallyallocatedmemorycanresultinthatdatabecominginaccessible.Ifthishappens frequently,eventuallytheoperatingsystemwillnolongerbeabletoallocatemorememoryfortheprocess.Oncetheprocessexits,theoperatingsystemisabletofreealldynamicallyallocatedmemoryassociatedwiththeprocess. Let'slookathowdynamicmemoryallocationcanbeusedforarrays. Normallywhenwewishtocreateanarrayweuseadeclarationsuchas


i n ta r r a y [ 1 0 ] ;

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 ) ; }

Ofcourse,suddenlyquittingasintheaboveexampleisnotalwaysappropriate,anddependsontheproblemyouaretryingtosolveandthearchitectureyouareprogrammingfor.Forexample,iftheprogramisasmall,noncriticalapplicationthat's runningonadesktopquittingmaybeappropriate.Howeveriftheprogramissometypeofeditorrunningonadesktop,youmaywanttogivetheoperatortheoptionofsavinghistediouslyenteredinformationinsteadofjustexitingtheprogram.Amemory allocationfailureinanembeddedprocessor,suchasmightbeinawashingmachine,couldcauseanautomaticresetofthemachine.Forthisreason,manyembeddedsystemsdesignersavoiddynamicmemoryallocationaltogether.

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

The r e a l l o c functionchangesthesizeoftheobjectpointedtoby p t r tothesizespecifiedby s i z e .Thecontentsoftheobjectshallbeunchangeduptothelesserofthenewandoldsizes.Ifthenewsizeislarger,thevalueofthenewlyallocatedportionof

92/118

10/24/13

C Programming/Print version - Wikibooks, open books for an open world

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 !

Thestatement" f r e e ( t e m p ) ; "will notfree t e m p > l e f t ,causingamemoryleak. BecauseCdoesnothaveagarbagecollector,Cprogrammersareresponsibleformakingsurethereisa f r e e ( ) exactlyonceforeachtimethereisa m a l l o c ( ) .Ifatreehasbeenallocatedonenodeatatime,thenitneedstobefreedonenodeatatime.

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

C Programming/Print version - Wikibooks, open books for an open world

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 ! " ;

Thisfeatureallowsstringswheremorethan256differentpossiblecharactersareneeded(althoughalsovariablelength c h a r stringscanbeused).Theyendwithazerovalued w c h a r _ t .Thesestringsarenotsupportedbythe < s t r i n g . h > functions.Insteadthey havetheirownfunctions,declaredin < w c h a r . h > .

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 .

The< s t r i n g . h > StandardHeader


Becauseprogrammersfindrawstringscumbersometodealwith,theywrotethecodeinthe < s t r i n g . h > library.Itrepresentsnotaconcerteddesigneffortbutrathertheaccretionofcontributionsmadebyvariousauthorsoveraspanofyears. First,threetypesoffunctionsexistinthestringlibrary: the m e m functionsmanipulatesequencesofarbitrarycharacterswithoutregardtothenullcharacter the s t r functionsmanipulatenullterminatedsequencesofcharacters the s t r n functionsmanipulatesequencesofnonnullcharacters.

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

C Programming/Print version - Wikibooks, open books for an open world

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 '

Beforecalling s t r c a t ( ) ,thedestinationmustcurrentlycontainanullterminatedstringorthefirstcharactermusthavebeeninitializedwiththenullcharacter(e.g. p e n T e x t [ 0 ]=' \ 0 ' ; ). Thefollowingisapublicdomainimplementationof s t r c a t :


# i n c l u d e< s t r i n g . h > / *s t r c a t* / 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 ) { c h a r* s=s 1 ; / *M o v ess ot h a ti tp o i n t st ot h ee n do fs 1 . * / w h i l e( * s! =' \ 0 ' ) s + + ; / *C o p yt h ec o n t e n t so fs 2i n t ot h es p a c ea tt h ee n do fs 1 . * / s t r c p y ( s ,s 2 ) ; r e t u r ns 1 ; }

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) ; }

C Programming/Print version - Wikibooks, open books for an open world

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* / ;

Thecollatingsequenceusedby s t r c m p ( ) isequivalenttothemachine'snativecharacterset.Theonlyguaranteeabouttheorderisthatthedigitsfrom ' 0 ' to ' 9 ' areinconsecutiveorder. Thefollowingisapublicdomainimplementationof s t r c m p :


# i n c l u d e< s t r i n g . h > / *s t r c m p* / i n t( s 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 ) { u n s i g n e dc h a ru c 1 ,u c 2 ; / *M o v es 1a n ds 2t ot h ef i r s td i f f e r i n gc h a r a c t e r s i ne a c hs t r i n g ,o rt h ee n d so ft h es t r i n g si ft h e y a r ei d e n t i c a l . * / w h i l e( * s 1! =' \ 0 '& &* s 1= =* s 2 ){ s 1 + + ; s 2 + + ; } / *C o m p a r et h ec h a r a c t e r sa su n s i g n e dc h a ra n d r e t u r nt h ed i f f e r e n c e . * / 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 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 ) ;

Important:Youmustensurethatthedestinationbuffer(s 1 )isabletocontainallthecharactersinthesourcearray,includingtheterminatingnullbyte.Otherwise, s t r c p y ( ) willoverwritememorypasttheendofthebuffer,causingabufferoverflow,which cancausetheprogramtocrash,orcanbeexploitedbyhackerstocompromisethesecurityofthecomputer.

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 ; }

C Programming/Print version - Wikibooks, open books for an open world

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 l e n ( ) functionshallcomputethenumberofbytesinthestringtowhich s points,notincludingtheterminatingnullbyte.Itreturnsthenumberofbytesinthestring.Novalueisusedtoindicateanerror. Thefollowingisapublicdomainimplementationof s t r l e n :


# i n c l u d e< s t r i n g . h > / *s t r l e n* / s i z e _ t( s t r l e n ) ( c o n s tc h a r* s ) { c o n s tc h a r* p=s ; / *L o o po v e rt h ed a t ai ns . * / w h i l e( * p! =' \ 0 ' ) p + + ; r e t u r n( s i z e _ t ) ( p-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 a t ( ) functionshallappendnotmorethan n bytes(anullbyteandbytesthatfollowitarenotappended)fromthearraypointedtoby s 2 totheendofthestringpointedtoby s 1 .Theinitialbyteof s 2 overwritesthenullbyteattheendof s 1 .A terminatingnullbyteisalwaysappendedtotheresult.Ifcopyingtakesplacebetweenobjectsthatoverlap,thebehaviorisundefined.Thefunctionreturns s 1 . Thefollowingisapublicdomainimplementationof s t r n c a t :


# i n c l u d e< s t r i n g . h > / *s t r n c a t* / 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 ) { c h a r* s=s 1 ; / *L o o po v e rt h ed a t ai ns 1 . * / w h i l e( * s! =' \ 0 ' ) s + + ; / *sn o wp o i n t st os 1 ' st r a i l i n gn u l lc h a r a c t e r ,n o wc o p y u pt onb y t e sf r o ms 1i n t oss t o p p i n gi fan u l lc h a r a c t e r i se n c o u n t e r e di ns 2 . I ti sn o ts a f et ou s es t r n c p yh e r es i n c ei tc o p i e sE X A C T L Yn c h a r a c t e r s ,N U L Lp a d d i n gi fn e c e s s a r y . * / w h i l e( n! =0& &( * s=* s 2 + + )! =' \ 0 ' ){ n ; s + + ; } i f( * s! =' \ 0 ' ) * s=' \ 0 ' ; r e t u r ns 1 ; }

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 ) ) ; }

C Programming/Print version - Wikibooks, open books for an open world

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 ; }

C Programming/Print version - Wikibooks, open books for an open world

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 ) ;

The m e m c p y ( ) functionshallcopy n bytesfromtheobjectpointedtoby s 2 intotheobjectpointedtoby s 1 .Ifcopyingtakesplacebetweenobjectsthatoverlap,thebehaviorisundefined.Thefunctionreturns s 1 . Becausethefunctiondoesnothavetoworryaboutoverlap,itcandothesimplestcopyitcan. Thefollowingisapublicdomainimplementationof m e m c p y :


# i n c l u d e< s t r i n g . h > / *m e m c p y* / 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 ) { c h a r* d s t=s 1 ; c o n s tc h a r* s r c=s 2 ; / *L o o pa n dc o p y . * / w h i l e( n -! =0 ) * d s t + +=* s r c + + ; r e t u r ns 1 ; }

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 ; }

C Programming/Print version - Wikibooks, open books for an open world

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 ; }

Thes t r c o l l ands t r x f r m functions


i n ts t r c o l l ( 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 x f r m ( c h a r* s 1 ,c o n s tc h a r* s 2 ,s i z e _ tn ) ;

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 ) ;

C Programming/Print version - Wikibooks, open books for an open world

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 ) ;

The s t r s t r ( ) functionshalllocatethefirstoccurrenceinthestringpointedtoby h a y s t a c k ofthesequenceofbytes(excludingtheterminatingnullbyte)inthestringpointedtoby n e e d l e .Thefunctionreturnsthepointertothematchingstringin h a y s t a c k ora nullpointerifamatchisnotfound.If n e e d l e isanemptystring,thefunctionreturns h a y s t a c k . Thefollowingisapublicdomainimplementationof s t r s t r :


# i n c l u d e< s t r i n g . h > / *s t r s t r* / 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 ) { s i z e _ tn e e d l e l e n ; / *C h e c kf o rt h en u l ln e e d l ec a s e . * / i f( * n e e d l e= =' \ 0 ' ) r e t u r n( c h a r* )h a y s t a c k ; n e e d l e l e n=s t r l e n ( n e e d l e ) ; f o r( ;( h a y s t a c k=s t r c h r ( h a y s t a c k ,* n e e d l e ) )! =N U L L ;h a y s t a c k + + ) i f( s t r n c m p ( h a y s t a c k ,n e e d l e ,n e e d l e l e n )= =0 ) r e t u r n( c h a r* )h a y s t a c k ; r e t u r nN U L L ; }

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 ) ;

C Programming/Print version - Wikibooks, open books for an open world

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 ) ;

The m e m s e t ( ) functionconverts c into u n s i g n e dc h a r ,thenstoresthecharacterintothefirst n bytesofmemorypointedtoby s . Thefollowingisapublicdomainimplementationof m e m s e t :


# i n c l u d e< s t r i n g . h > / *m e m s e t* / v o i d* ( m e m s e t ) ( v o i d* s ,i n tc ,s i z e _ tn ) { u n s i g n e dc h a r* u s=s ; u n s i g n e dc h a ru c=c ; w h i l e( n -! =0 ) * u s + +=u c ; r e t u r ns ; }

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 ) ;

C Programming/Print version - Wikibooks, open books for an open world

Thisfunctionreturnsalocalespecificerrormessagecorrespondingtotheparameter.Dependingonthecircumstances,thisfunctioncouldbetrivialtoimplement,butthisauthorwillnotdothatasitvaries. TheSingleUnixSystemVersion3hasavariant, s t r e r r o r _ r ,withthisprototype:


i n ts t r e r r o r _ r ( i n te r r c o d e ,c h a r* b u f ,s i z e _ tb u f l e n ) ;

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

C Programming/Print version - Wikibooks, open books for an open world

definesapointertoan i n t ,andalsomakesitpointtotheparticularintegercontainedin v a r i a b l e . The'*'iswhatmakesthisanintegerpointer.Tomakethepointerpointtoadifferentinteger,usetheform


p o i n t e r=& s a n d w i c h e s ;

Where&isthe addressof operator.OftenprogrammerssetthevalueofthepointertoNULL(astandardmacrodefinedas0or(void*)0)likethis:


p o i n t e r=N U L L ;

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 ;

Itisoftencommonpracticetomakea typesynonymsowedon'thavetotype"structmystruct"allthetime.Callowsusthepossibilitytodosousinga t y p e d e f statement,whichaliasesatype:


t y p e d e fs t r u c t { . . . }M y s t r u c t ;

The s t r u c t itselfhasnoname(bytheabsenceofanameonthefirstline),butitisaliasedas M y s t r u c t .Thenyoucanuse


M y s t r u c ts t r u c t u r e ;

Notethatitiscommonplace,andgoodstyletocapitalizethe firstletterofatypesynonym.Howeverintheactualdefinitionweneedtogivethestructa tagsowecanrefertoit:wemayhavea recursivedatastructureofsomekind.Fortreesorchained lists,weneedapointertothesamedatatypeinthestruct.Duringcompilation,thetypesynonymisnotknowntothecompilerandtherewillbeanerror.Toavoidthis,itisnecessarytoletthecompilerknowthenamerightfromthestart(Notethatthe structkeywordisused onlyinsidethestructure!Afterthedeclaration,thecompiler knowsthatthetypesynonymreferstoa struct):


t y p e d e fs t r u c tM y s t r u c t { . . . s t r u c tM y s t r u c t*p M y s t r u c t }M y s t r u c t ;

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 ;

Theprogrammercanaccesseither u . i or u . d ,butnotbothatthesametime.Since u . i and u . d occupythesameareaofmemory,modifyingonemodifiesthevalueoftheother,sometimesinunpredictableways.

en.wikibooks.org/wiki/C_Programming/Print_version

104/118

10/24/13
Thesizeofaunionisthesizeofitslargestmember.

C Programming/Print version - Wikibooks, open books for an open world

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 ; }

Thisistheverybarebonesofaclientinpractice,wewouldcheckeveryfunctionthatwecallforfailure,however,errorcheckinghasbeenleftoutforclarity. Asyoucansee,thecodemainlyrevolvesaround d e s t whichisastructoftype s o c k a d d r _ i n .Thisstructstoresinformationaboutthemachinewewanttoconnectto.


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 ) ;

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* /

Nowwegetontotheinterestingpart: Thefirstlineuses m e m s e t ( ) tozerothestruct. Thesecondlinesetstheaddressfamily.Thisshouldbethesamevaluethatwaspassedasthefirstparameterto s o c k e t ( ) formostpurposes A F _ I N E T willserve.

en.wikibooks.org/wiki/C_Programming/Print_version

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

105/118

10/24/13

C Programming/Print version - Wikibooks, open books for an open world

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

C Programming/Print version - Wikibooks, open books for an open world

Oncewehave"session"socketwecanhandleitinthesamewayaswiththeclient,using s e n d ( ) and r e c v ( ) tohandledatatransfers. Notethatthisservercanonlyacceptoneconnectionatatimeifyouwanttosimultaneouslyhandlemultipleclientsthenyou'llneedto f o r k ( ) offseparateprocesses,orusethreads,tohandletheconnections.

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 ) ;

Thisfunctionobtainsinformationaboutadomainnameandstoresitina h o s t e n t struct.Themostusefulpartofa h o s t e n t structureisthe ( c h a r * * )h _ a d d r _ l i s t field,whichisanullterminatedarrayoftheIPaddressesassociatedwiththatdomain.Thefield h _ a d d r isapointertothefirstIPaddressinthe h _ a d d r _ l i s t array.Returns N U L L onfailure.

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

C Programming/Print version - Wikibooks, open books for an open world

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

Notethatw*(x*(y*i+j)+k)+lisequaltow*x*y*i+w*x*j+w*k+l,butusesfeweroperations(seeHorner'sMethod(http://en.wikipedia.org/wiki/Horner%27s_method)).Itusesthesamenumberofoperationsasaccessingastaticarraybydim4[i][j][k][l],so shouldnotbeanyslowertouse. Theadvantagetousingthismethodisthatthearraycanbepassedfreelybetweenfunctionswithoutknowingthesizeofthearrayatcompiletime(sinceCseesitasa1dimensionalarray,althoughsomewayofpassingthedimensionsisstillnecessary), andtheentirearrayiscontiguousinmemory,soaccessingconsecutiveelementsshouldbefast.Thedisadvantageisthatitcanbedifficultatfirsttogetusedtohowtoindextheelements.

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 ; } ;

s t r u c ts t r i n g* c r e a t e _ s t r i n g ( c o n s tc h a r* i n i t i a l ){ a s s e r t( i n i t i a l! =N U L L ) ; s t r u c ts t r i n g* n e w _ s t r i n g=m a l l o c ( s i z e o f ( * n e w _ s t r i n g ) ) ; i f( n e w _ s t r i n g! =N U L L ){ n e w _ s t r i n g > s i z e=s t r l e n ( i n i t i a l ) ; n e w _ s t r i n g > d a t a=s t r d u p ( i n i t i a l ) ; } r e t u r nn e w _ s t r i n g ; }

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* / }

Itisoftenusefultocombinedestructorswith #Nullingfreedpointers. Sometimesitisusefultohidethedefinitionoftheobjecttoensurethattheclientdoesnotallocateitmanually.Todothis,thestructureisdefinedinthesourcefile(oraprivateheaderfilenotavailabletousers)insteadoftheheaderfile,andaforward declarationisputintheheaderfile:


s t r u c ts t r i n g ; s t r u c ts t r i n g* c r e a t e _ s t r i n g ( c o n s tc h a r* i n i t i a l ) ; 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 ) ;

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 ;

C Programming/Print version - Wikibooks, open books for an open world

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 )

(Toseewhythemacroiswrittenthisway,see #Macroconventions.)Also,whenthistechniqueisused,destructorsshouldzerooutthepointerthattheyarepassed,andtheirargumentmustbepassedbyreferencetoallowthis.Forexample,here'sthe destructorfrom #Constructorsanddestructorsupdated:


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 & & * 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* / * s = N U L L ; / *z e r ot h ea r g u m e n t* / }

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

C Programming/Print version - Wikibooks, open books for an open world

variablelengthdatastructure(astructurewhoselastitemisa"zerolengtharray"). [19] resizeablemultidimensionalarrays various"#pragma"settingstocompilequickly,togeneratefastcode,ortogeneratecompactcode. bitmanipulation,especiallybitrotationsandthingsinvolvingthe"carry"bit storagealignment Arrayswhoselengthiscomputedatruntime.

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/llvmcommits@cs.uiuc.edu/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

C Programming/Print version - Wikibooks, open books for an open world

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

C Programming/Print version - Wikibooks, open books for an open world

p u t s( " H it h e r e ! " ) ; p u t s( " S t r a n g et h i n g sa r ea f o o t . . . " ) ;

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 )

Specificcompilersmay(inanonstandardcompliantmode)alsotreatsomeotherwordsaskeywords,including a s m , c d e c l , f a r , f o r t r a n , h u g e , i n t e r r u p t , n e a r , p a s c a l , t y p e o f . VeryoldcompilersmaynotrecognizesomeoralloftheC89keywords c o n s t , e n u m , s i g n e d , v o i d , v o l a t i l e aswellastheC99keywords. Seealsothelistofreservedidentifiers(http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/topic/com.ibm.vacpp7a.doc/language/ref/clrc02reserved_identifiers.htm).

ListofStandardHeaders
ANSIC(C89)/ISOC(C90)headers:

< 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 > < s t d d e f . h > < s t d i o . h >

< s t d l i b . h > < s t r i n g . h > < t i m e . h >

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):

< c o m p l e x . h > < f e n v . h >

< i n t t y p e s . h > < s t d b o o l . h >

< s t d i n t . h > < t g m a t h . h >

en.wikibooks.org/wiki/C_Programming/Print_version

112/118

10/24/13

C Programming/Print version - Wikibooks, open books for an open world

TableofOperators
Operatorsinthesamerowofthistablehavethesame precedenceandtheorderofevaluationisdecidedbythe associativity(lefttoright or righttoleft ).Operatorsclosertothetopofthistablehave higherprecedencethanthoseinasubsequent group. Operators Description Postfixoperators ExampleUsage Associativity

( ) [ ]

functioncalloperator arrayindexoperator memberaccessoperator foranobjectofstruct/uniontype orareferencetoit memberaccessoperator forapointertoanobjectof struct/uniontype

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
! ~

logicalnotoperator bitwisenotoperator unaryplus/minusoperators

! 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 )

postincrement/decrementoperators n u m + + preincrement/decrementoperators + + n u m addressofoperator indirectionoperator sizeofoperator forexpressions sizeofoperator fortypes castoperator


& d a t a * p t r s i z e o f1 2 3 s i z e o f( i n t ) ( f l o a t ) i

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

b i t s< <s h i f t _ l e n b i t s> >s h i f t _ l e n

RelationalInequalityOperators

en.wikibooks.org/wiki/C_Programming/Print_version

113/118

10/24/13
<>< => =

C Programming/Print version - Wikibooks, open books for an open world


lessthan,greaterthan,lessthanor i<n u m _ e l e m e n t s equalto,greaterthanorequalto operators Lefttoright

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
= + ==* =/ = % =& =| =^ = < < => > =

assignmentoperator shorthandassignmentoperators (f o oo p =b a r represents


f o o=f o oo pb a r )

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

C Programming/Print version - Wikibooks, open books for an open world


s i z e o f givesthesizeinunitsof c h a r s.These"Cbytes"neednotbe8bitbytes(thoughcommonlytheyare)thenumberofbitsis

givenbythe C H A R _ B I T macrointhe l i m i t s . h header.


c h a r

Signednessisimplementationdefined. Anyencodingof8bitsorless(e.g.ASCII)canbeusedtostorecharacters. Integeroperationscanbeperformedportablyonlyfortherange0~127. Allbitscontributetothevalueofthe char,i.e.thereareno"holes"or"padding"bits.

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

Usedtoreducememoryusagewhenthevaluesuseddonotvarywidely. ThefloatingpointformatusedisimplementationdefinedandneednotbetheIEEEsingleprecisionformat. u n s i g n e d cannotbespecified.

d o u b l e

sizeof f l o a t

Representsthe"normal"sizeofdatatheprocessordealswiththisisthefloatingpointdatatypeusednormally. ThefloatingpointformatusedisimplementationdefinedandneednotbetheIEEEdoubleprecisionformat. u n s i g n e d cannotbespecified.

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

C Programming/Print version - Wikibooks, open books for an open world

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)

valueofanullpointer. Pointerstodifferenttypesmayhavedifferentrepresentations,whichmeanstheycouldalsobeofdifferentsizes.Sotheyarenot convertibletooneanother. Eveninanimplementationwhichguarantessalldatapointerstobeofthesamesize,functionpointersanddatapointersarein generalincompatiblewitheachother. Forfunctionstakingvariablenumberofarguments,theargumentspassedmustbeofappropriatetype,soeven 0 mustbecast totheappropriatetypeinsuchfunctioncalls.

[ 6 ] t y p e[ i n t e g e r ]

Thebrackets([ ] ) followtheidentifiernameinadeclaration. integersizeof t y p e Inadeclarationwhichalsoinitializesthearray(includingafunctionparameterdeclaration),thesizeofthearray(the integer)can

en.wikibooks.org/wiki/C_Programming/Print_version

116/118

10/24/13
(array)

C Programming/Print version - Wikibooks, open books for an open world


beomitted. t y p e[ ] isnotthesameas t y p e * .Onlyundersomecircumstancesonecanbeconvertedtotheother.

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 )

Functionsdeclaredwithoutanystorageclassare e x t e r n . Theparentheses(( ) ) followtheidentifiernameinadeclaration,e.g.a2argfunctionpointer: i n t( *f p t r )( i n ta r g 1 ,i n ta r g 2 ) .

(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.

C Programming/Print version - Wikibooks, open books for an open world

TextisavailableundertheCreativeCommonsAttribution/ShareAlikeLicenseadditionaltermsmayapply.Byusingthissite,youagreetotheTermsofUseandPrivacyPolicy.

en.wikibooks.org/wiki/C_Programming/Print_version

118/118

You might also like