C Programming
C Programming
CProgramming/Printversion
CProgramming
Thecurrent,editableversionofthisbookisavailableinWikibooks,theopencontenttextbookscollection,at [Link]
Permissionisgrantedtocopy,distribute,and/ormodifythisdocumentunderthetermsoftheCreativeCommonsAttributionShareAlike3.0License.
WhylearnC?
[Link],MacOSX,andGNU/[Link] systems,[Link],Perl,PHP,andPythonareallwritteninC. Bywayofanalogy,let'ssaythatyouweregoingtobelearningSpanish,Italian,French,[Link]?JustasLatinwasthebasisofallofthoselanguages,knowingCwillenableyoutounderstandand [Link].
WhyC,andnotassemblylanguage?
Whileassemblylanguagecanprovidespeedandmaximumcontroloftheprogram,Cprovidesportability. [Link],oneofthemainstrengthsofCisthatitcombinesuniversalityandportabilityacrossvariouscomputer architectureswhileretainingmostofthecontrolofthehardwareprovidedbyassemblylanguage. Forexample,CprogramscanbecompiledandrunontheHP50gcalculator(ARMprocessor),theTI89calculator(68000processor),PalmOSCobaltsmartphones(ARMprocessor),theoriginaliMac(PowerPC),theArduino(AtmelAVR),andtheIntel iMac(IntelCore2Duo).Eachofthesedeviceshasitsownassemblylanguagethatiscompletelyincompatiblewiththeassemblylanguageofanyother. Assembly,whileextremelypowerful,[Link],[Link]"whatyouseeisallyou get"language:aCstatementcorrespondstoatmostahandfulofassemblystatements,everythingelseisprovidedbylibraryfunctions. SoisitanywonderthatCissuchapopularlanguage? Liketopplingdominoes,[Link](likeOpenGL, orGTK),[Link],games,[Link] [Link]......
WhyC,andnotanotherlanguage?
TheprimarydesignofCistoproduceportablecodewhilemaintainingperformanceandminimizingfootprint,asisthecaseforoperatingsystemsorotherprogramswherea"highlevel"[Link] languagewhosefeaturesareunlikelytodisappearforalongtimeandhasbeenportedtomost,ifnotall,platforms. Forexample,CprogramscanbecompiledandrunontheHP50gcalculator(ARMprocessor),theTI89calculator(68000processor),PalmOSCobaltsmartphones(ARMprocessor),theoriginaliMac(PowerPC),theArduino(AtmelAVR),andtheIntel iMac(IntelCore2Duo).Whilenearlyallpopularprogramminglanguageswillrunonatleastoneofthesedevices,Cmaybetheonlyprogramminglanguagethatrunsonmorethan3ofthesedevices. [Link],[Link],pointersandarraysaredesignedtostructure,andmanipulatememoryinanefficient, [Link],[Link],whichinevitablymeansthatmemorydeallocationistheburdenofthe [Link],sincedealingwithmemoryallocationwhenbuildingahighlevelprogramisahighlyerrorprone [Link],whendealingwithlowlevelcodesuchasthepartoftheOSthatcontrolsadevice,Cprovidesauniform,[Link]. WhilePerl,PHP,PythonandRubymaybepowerfulandsupportmanyfeaturesnotprovidedbydefaultinC,[Link],mostsuchlanguagesinitiallyreliedonbeingwritteninC(oranotherhigh performanceprogramminglanguage),andwouldrequiretheirimplementationbeportedtoanewplatformbeforetheycanbeused. Aswithallprogramminglanguages,whetheryouwanttochooseCoveranotherhighlevellanguageisamatterofopinionandbothtechnicalandbusinessrequirements.
[Link]/wiki/C_Programming/Print_version
1/118
10/24/13
History
Thefieldofcomputingasweknowittodaystartedin1947withthreescientistsatBellTelephoneLaboratoriesWilliamShockley,WalterBrattain,andJohnBardeenandtheirgroundbreakinginvention:thetransistor.In1956,thefirstfullytransistor basedcomputer,theTX0,wascompletedatMIT.Thefirstintegratedcircuitwascreatedin1958byJackKilbyatTexasInstruments,butthefirsthighlevelprogramminglanguageexistedevenbeforethen. "TheFortranproject"[Link]" TheIBMMathematical Formula TranslatingSystem",theprojecthadthepurposeofcreatingandfosteringdevelopmentofaprocedural,imperativeprogramminglanguage [Link](comparedtoassemblylanguage)andspeed(Fortranprogramsrannearlyasfastas,andinsomecases, justasfastas,programswritteninassembly).Furthermore,Fortranwaswrittenatahighenoughlevel(andthuswasmachineindependentenough)[Link](Algol58)was [Link](CPL)wasthencreatedoutofAlgol60in1963.In1967,itevolvedintoBasicCPL,whichwasitself,[Link],Bwastheroot ofC,createdin1971. BwasthefirstlanguageinC'[Link],alsoworkingatBellLabs, [Link],C,[Link],andthenC,whichresultedinamoreportableoperatingsystem. [Link],systemprogrammerscouldsimplywritethefewsystemdependentpartsrequiredforthe machine,[Link],itsimplymadesensetoalsowritenewutilitiesinC. TheAmericanNationalStandardsInstitutebeganworkonstandardizingtheClanguagein1983,[Link],ANSIX3.1591989"ProgrammingLanguageC",servedasthebasisforallimplementationsofC compilers.Thestandardswerelaterupdatedin1990and1999,allowingforfeaturesthatwereeitherincommonuse,orwereappearinginC++.
Whatyouneedbeforeyoucanlearn
GettingStarted
[Link],butnospecialknowledgeisneeded. BeforeyoucanstartprogramminginC,youwillneeda [Link]. [1] PopularCcompilersInclude: Name MicrosoftVisual StudioExpress TinyCCompiler (TCC) Clang GNUCCompiler Website VisualStudio([Link] us/products/2010editions/visualcppexpress) tinycc([Link] clang([Link] gcc([Link] Platform Windows GNU/Linux,Windows GNU/Linux,Windows,Unix,OSX GNU/Linux,MinGW(Windows) ([Link] License FreeVersion LGPL UniversityofIllinois/NCSALicense ([Link] GPL Details Powerfulandstudentfriendlyversionofan industrystandardcompiler. Small,fastandsimplecompiler. Afrontendwhichcompiles(Objective)C/C++ usingaLLVMbackend. [Link] systems.
TheminimumsoftwarerequirementstoprograminCisatexteditor,[Link] editors(seeListofTextEditors),amongthemostpopularareNotepad++forWindows,SublimeText,[Link],whichmakescodeeasiertoread ataglance,andtospotsyntaxerrors. Thoughnotabsolutelyneeded,manyprogrammerspreferandrecommendusinganIntegrateddevelopmentenvironment(IDE )[Link],combinedintooneconvenientpackage,usually [Link],linker,[Link],atoolthatwillpreserveyourCsourcecodeaftercompilationandenable youtodosuchthingsasstepthroughitmanually,oralterdataasanaidtofindingandcorrectingprogrammingerrors. ForbeginnersitisrecommendednottouseanIDE,[Link]. 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([Link] Linux Netbeans([Link] Anjuta([Link] geany([Link] lcc([Link] Crossplatform Linux Crossplatform Windows
[Link]/wiki/C_Programming/Print_version
2/118
10/24/13
Xcode PellesC DevC++ MicrosoftVisualStudio Express CodeLite Code::Blocks Xcode([Link] PellesC([Link] DevC++([Link]
Footnotes
1. Actually,GCC's(GNUCCompiler) cc(CCompiler)[Link]'sassembly,[Link] as(assembler)[Link] program cpp(CPreProcessor),whichisnottobeconfusedwith c++thecompiler. 2. [Link] 3. [Link]
UsingaCompiler
DevC++
DevC++isanIntegratedDevelopmentEnvironment(IDE)fortheC++programminglanguage,availablefromBloodshedSoftware([Link] C++isaprogramminglanguagewhichcontainswithinitself,mostoftheClanguage,[Link]++compilerswillcompileCprograms,sometimeswithafewadjustments(likeinvokingthemwithadifferentnameorcommandlineswitch). Therefore,youcanuseDevC++forCdevelopment. However,DevC++[Link]++package,althoughtheyarecompletelydifferentprojects. DevC++simplyprovidesaneditor,syntaxhighlighting,somefacilitiesforthevisualisationofcode(likeclassandpackagebrowsing)[Link]++analysestheerrormessagesproducedbythe compilerandattemptstodistinguishthelinenumbersfromtheerrorsthemselves,theuseofothercompilersoftwareisdiscouragedsincetheformatoftheirerrormessagesislikelytobedifferent. ThelatestversionofDevC++[Link],[Link],[Link]. AversionofDevC++[Link],[Link].([Link].)Mostofthegraphicaltexteditors,andothercommoneditorssuchas emacsand vi(m), supportsyntaxhighlighting.
GCC
TheGNUCompilerCollection(GCC)isafreesetofcompilersdevelopedbytheFreeSoftwareFoundation.
StepsforObtainingtheGCCCompilerifYou'reonGNU/Linux On GNU/Linux, InstallingtheGNUCCompilercanvaryinmethodfromdistributiontodistribution.(Typein ccvtoseeifitisinstalledalready.) ForRedhat,getaGCCRPM,[Link](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 ,[Link]. ForSlackware,thepackageisavailableontheirwebsite([Link] i n s t a l l p k gg c c x x x x x . t g z ForGentoo,[Link](asroot) e m e r g eu a vg c c . ForArchLinux,installtheGCCcompiler(asroot)byusing p a c m a nSg c c . Ifyoucannotbecomeroot,gettheGCCtarballfrom[Link] YoucanusesomecommercialCcompiler/IDE.
[Link]/wiki/C_Programming/Print_version
3/118
10/24/13
StepsforObtainingtheGCCCompilerifYou'reonBSDFamilySystems ForMacOSX,FreeBSD,NetBSD,OpenBSD,DragonFlyBSD,DarwintheportofGNUgccisavailableinthebasesystem,oritcouldbeobtainedusingtheportscollectionorpkgsrc.
StepsforObtainingtheGCCCompilerifYou'reonWindows TherearetwowaystouseGCConWindows:[Link],[Link],andtakeslessdiskspace. TogetMinGW,dothis: 1. Goto[Link] 2. Oncethedownloadisfinished,[Link],orthetoolMake,butthesearen'tnecessary. 3. [Link]"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. Goto[Link] Click"run"inthewindowthatpopsup,andclick"next"severaltimes,acceptingallthedefaultsettings. ChooseanyoftheDownloadsites("[Link]",etc.)whenthatwindowcomesuppress"next"andtheCygwininstallershouldstartdownloading. Whenthe"SelectPackages"windowappears,scrolldowntotheheading"Devel"andclickonthe"+"[Link],scrolldownandfindthe"gcccore"[Link]"Skip", anditshouldchangetosomenumberlike"3.4"etc.(theversionnumber),andan"X"willappearnextto"gcccore"andseveralotherrelatedpackagesthatwillnowbedownloaded. 5. Click"next"[Link]'rewaitingfortheinstallationtofinish,[Link],you [Link],itisnotideal. 6. OncetheCygwindownloadsarefinishedandyouhaveclicked"next",[Link],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,[Link],GCCisnotonlyaCcompiler,butafamilyofcompilersforseverallanguages,suchasC++,Ada,Java,andFortran. Oncegccisinstalled,[Link].handimplementedinmyfun_a.candmyfun_b.c,thenitisenough towrite
g c c m a i n . cm y f u n _ a . cm y f u n _ b . c
Embeddedsystems
MostCPUsaremicrocontrollersinembeddedsystems,oftenprogrammedinC,butmostofthecompilersmentionedabove(exceptGCC)[Link],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 ; }
[Link]/wiki/C_Programming/Print_version
4/118
10/24/13
Thisprogramprints"Hello,world!"andthenexits. EnterthiscodeintoyourtexteditororIDE,andsaveitas"hello.c".
Then,presumingyouareusingGCC,type g c coh e l l oh e l l o . c .[Link]'ohello'tellsittocallthecompiledprogram'hello'. Ifyouhaveenteredthiscorrectly,[Link],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 [Link] 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>[Link],youoftenhavetopullinextraoptionalcomponentswhenyouneedthem. <stdio.h>containsdescriptionsofstandardinput/outputfunctions
whichyoucanusetosendmessagestoauser,ortoreadinputfromauser.
i n tm a i n ( v o i d ) issomethingyou'[Link] [Link],[Link],oneCprogramcanbescatteredacrossmultiplefiles,soyouwon'talwaysfindamain
theendofthestring.
r e t u r n0 ; willreturnzero(whichistheintegerreferredtoonline3)[Link](GCC4complainsifitdoesn'twhencompiling).Anonzerovalueisreturnedtoindicateawarningorerror.
Introexercise
IntroductoryExercises
OnGCC
IfyouareusingaUnix(like)system,suchasGNU/Linux,MacOSX,orSolaris,[Link]:
g c cf i r s t . c
Thenruntheprogrambytyping:
. / a . o u t
or,IfyouareusingCygwin.
a . e x e
YoushouldnowseeyourveryfirstCprogram.
[Link],[Link],[Link]:
c
indicatesthatthecompilerissupposedtogeneratean objectfile,whichcanbelaterlinkedtootherfilestoformafinalprogram.
o
indicatesthatthenextparameteristhenameoftheresultingprogram(orlibrary).Ifthisoptionisnotspecified,thecompiledprogramwill,forhistoricreasons,endupinafilecalled"[Link]"or"[Link]"(forcygwinusers).
g 3
[Link]/wiki/C_Programming/Print_version
5/118
10/24/13
indicatesthat debugginginformationshouldbeaddedtotheresultsofcompilation.
O 2f f a s t m a t h
indicatesthatthecompilationshouldbeoptimized.
WW a l lf n o c o m m o nW c a s t a l i g nW r e d u n d a n t d e c l sW b a d f u n c t i o n c a s tW w r i t e s t r i n g sW a g g r e g a t e r e t u r nW s t r i c t p r o t o t y p e sW m i s s i n g p r o t o t y p e s
indicatesthatgccshouldwarnaboutmanytypesofsuspiciouscodethatarelikelytobeincorrect.
E
indicatesthatgccshouldonlypreprocessthecodethisisusefulwhenyouarehavingtroubleunderstandingwhatgccisdoingwith#includeand#define,amongotherthings. Alltheoptionsarewelldocumentedinthemanualpage([Link]
theclassicalhelloworldprogram
Thebasichelloworldprogram,fromtheK+RbookonC,isoftenworthmemorising,justforthestructureofthemainfunctionwhichacceptsswitches,justlikegccisaprogramwithamainfunctionthatacceptsswitches.
OnIDEs
IfyouareusingacommercialIDEyoumayhavetoselectconsoleproject,[Link],butyoushouldhaveamenubuttonsoyoucanjustrunthe executablefromtheIDE. OnecanalsofindopensourceIDE'slikeEclipse,[Link].
[Link]/wiki/C_Programming/Print_version
6/118
10/24/13
BeginningC Preliminaries
BasicConcepts
BeforeonegetstoodeepintolearningCsyntaxandprogrammingconstructs,itisbeneficialtolearnthemeaningofafewkeytermsthatarecentraltoathoroughunderstandingofC.
BlockStructure,Statements,Whitespace,andScope
Nowwe [Link]'refamiliarwithPASCAL,youmayhavehearditreferredtoasa [Link](andyou'llfindoutwhywhenyougooverfunctionsin detail)butitisstillveryimportanttounderstandwhatblocksareandhowtousethem. Sowhatisina block?Generally,ablockconsistsofexecutable statements. Beforewesaywhatablockis,what'sastatement?Onewaytoputitisthatstatementsaretextthecompilerwillattempttoturnintoexecutableinstructions,[Link] 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* /
[Link]'lllearnalittlemoreaboutscopeinasecond. Whitespacereferstothetab,spaceandnewline/EOL(EndOfLine)[Link],it'shardtoappreciatewhitespaceuntilit'[Link],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 ;
[Link]/wiki/C_Programming/Print_version
7/118
10/24/13
[Link],itiscommonpracticetousespaces(andtabs)[Link],loop,orotherstatementtoorganizeyourcode. InC,mostofthetimewedonotwantotherfunctionsorotherprogrammer'[Link]. [Link], local and global .Whenwespeakofsomethingbeing global ,wespeakofsomethingthatcanbeseenormanipulatedfromanywhereinthe [Link] 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
[Link],[Link] ofrequestingafunctiontoperformitstaskiscalleda functioncall .Manyfunctionsrequireacallertohanditcertainpiecesofdataneededtoperformitstaskthesearecalled [Link]'re finishedthisiscalleda returnvalue(thereturnvalueintheaboveprogramis 0). Thethingsyouneedtoknowbeforecallingafunctionare: Whatthefunctiondoes Thedatatype(discussedlater)oftheargumentsandwhattheymean Thedatatypeofthereturnvalueandwhatitmeans Allcodeotherthanglobaldatadefinitionsanddeclarationsneedstobeapartofafunction. Usually,you'[Link],andonlyone, mainfunction,whichiswheretheprogrambeginsexecuting. Wewilldiscussfunctionsinmoredetailinalaterchapter,CProgramming/Proceduresandfunctions.
TheStandardLibrary
In1983,whenCwasintheprocessofbecomingstandardized,theAmericanNationalStandardsInstitute(ANSI)formedacommitteetoestablishastandardspecificationofCknownas"ANSIC".Thatstandardspecificationcreatedabasicsetof functionscommontoeachimplementationofC,[Link]/output,stringmanipulation,mathematics,files,[Link] doesnotprovidefunctionsthataredependentonspecifichardwareoroperatingsystems,likegraphics,sound,[Link]"Hello,World",program,aStandardLibraryfunctionisused p r i n t f whichoutputslinesoftexttothestandardoutput stream.
Compiling
HavingcoveredthebasicconceptsofCprogramming,wecannowbrieflydiscusstheprocessof compilation.
Likeanyprogramminglanguage,[Link] iscomprehensibletoa
[Link]/wiki/C_Programming/Print_version
8/118
10/24/13
Likeanyprogramminglanguage,[Link] iscomprehensibletoa [Link] compileriswhattakesthiscode,andtranslatesitintothemachinecode. Tothosenewtoprogramming,[Link],translateeverythingintomachinecode,[Link],[Link],foralargeproject,the [Link],ifyoumakeachangetoasinglesourcefile,youwouldrathernothavetorecompilethe entireapplication. Todealwiththeseproblems,compilersbreaktheirjobdownintostepsforeachsourcefile(each . c file),thecompilerreadsthefile,readsthefilesitreferenceswith # i n c l u d e ,[Link]"objectfile"(. o ).Once everyobjectfileismade,a"linker"[Link],ifyouchangeonesourcefile,onlythatfileneedstoberecompiledandthentheapplicationneedstoberelinked. Withoutgoingintothepainfuldetails,itcanbebeneficialtohaveasuperficialunderstandingofthecompilationprocess.
Preprocessor
Thepreprocessorprovidestheabilityfortheinclusionofheaderfiles,macroexpansions,conditionalcompilation,[Link] [Link],[Link] language. InClanguage,allpreprocessordirectivesbeginwiththepoundcharacter(#).YoucanseeonepreprocessordirectiveintheHelloworldprogramintroducedinAtasteofC: Example:
# i n c l u d e< s t d i o . h >
SyntaxChecking
[Link],youmaygetmessagesorwarningsindicatingpotentialissueswithyourprogram(suchasastatementalwaysbeingtrueorfalse,etc.) Whenanerrorisdetectedintheprogram,thecompilerwillnormallyreportthefilenameandlinethatispreventingcompilation.
ObjectCode
[Link]'tbeexecutedyet,asithastocompletethelinkingstage. It'simportanttonoteafterdiscussingthebasicsthatcompilationisa"onewaystreet".Thatis,compilingaCsourcefileintomachinecodeiseasy,but"decompiling"(turningmachinecodeintotheCsourcethatcreatesit)[Link] exist,buttheyrarelycreateusefulcode.
Linking
[Link],whichisoftenpartofacompiler. Commonerrorsduringthisstageareeithermissingfunctions,orduplicatefunctions.
Automation
ForlargeCprojects,manyprogrammerschoosetoautomatecompilation,bothinordertoreduceuserinteractionrequirementsandtospeeduptheprocessbyonlyrecompilingmodifiedfiles. Mostintegrateddevelopmentenvironmentshavesomekindofprojectmanagement,[Link],makeandMakefilesareoftenusedtoaccomplishthesame.
Structureandstyle
CStructureandStyle
[Link],comments,[Link] actuallyprogramminginC. Asabeginningprogrammer,thepointofcreatingstructureintheprograms'codemightnotbeclear,asthecompilerdoesn'[Link],asprogramsbecomecomplex,chancesarethatwritingtheprogramhasbecomeajoint effort.(Orothersmightwanttoseehowitwasaccomplished.)Therefore,thecodeisnolongerdesignedpurelyforacompilertoread. Inthefollowingsections,wewillattempttoexplaingoodprogrammingpracticesthatwillinturnmakeyourprogramsclearerandmoreeffective.
Introduction
InC,[Link],[Link],astatementshouldbekeptonitsownline,asshownintheexamplebelow:
# i n c l u d e< s t d i o . h >
[Link]/wiki/C_Programming/Print_version
9/118
10/24/13
i n tm a i n ( v o i d ) { p r i n t f ( " H e l l o ,W o r l d ! \ n " ) ; r e t u r n0 ; }
Thefollowingblockofcodeisessentiallythesame:whileitcontainsexactlythesamecode,andwillcompileandexecutewiththesameresult,theremovalofspacingcausesanessentialdifferencemakingithardertoread:
# i n c l u d e< s t d i o . h > i n tm a i n ( v o i d ){ p r i n t f ( " H e l l o ,W o r l d ! \ n " ) ; r e t u r n0 ; }
LineBreaksandIndentation
[Link],whichcanbeveryimportantwhenreturningtoyourcodewhenyou wanttomaintainit.
LineBreaks
Withminimallinebreaks,codeisbarelyreadablebyhumans,andmaybehardtodebugorunderstand:
Ratherthanputtingeverythingononeline,[Link],thecodewilllooklikethis:
BlankLines
[Link] 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 .{
[Link]/wiki/C_Programming/Print_version
10/118
10/24/13
5 .i n ti = 0 ; 6 . 7 .p r i n t f ( " H e l l o ,W o r l d ! " ) ; i 8 .f o r( = 0 ;i < 1 ;i + + ) 9 .{ 1 0 .p r i n t f ( " \ n " ) ; 1 1 .b r e a k ; 1 2 .} 1 3 .r e t u r n0 ; 1 4 .}
Butthisstillisn'tasreadableasitcanbe.
Indentation
Althoughaddingsimplelinebreaksbetweenkeyblocksofcodecanmakecodeeasiertoread,[Link]:indentation [Link]:
Manytexteditors
Comments
[Link](andtheirpurpose)aswellasprovidingavisual"split"[Link] 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,[Link]. Thissectionisgoingtofocusonthevarioususesofeachformofcommentary.
SinglelineComments
[Link]/wiki/C_Programming/Print_version
11/118
10/24/13
/ /l o o pv a r i a b l e .
/ / E x i t s' f o r 'l o o p .
MultilineComments
[Link]/licensingnotices,[Link]: Theymakeyourfunctionseasiertounderstand,[Link] supposedtodo,thenitismucheasiertofindthepieceofcodethatisresponsibleifanerroroccurs.
Singlelinecomments
[Link]. Finally,ifyouliketohaveaestheticallypleasingsourcecode,[Link].
/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 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 . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
[Link]/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 .
[Link]. 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'[Link]. CommentswritteninsourcefilescanbeusedfordocumentingsourcecodeautomaticallybyusingpopulartoolslikeDoxygen[4][5]
Links
1. Severalprogrammersrecommend"[Link]."[1]([Link] ([Link] tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5]([Link] 3. [[Link] 4. "CodingConventionsforC++andJava"([Link] Thisdeliberatechoicewasmadebecausealigningthoseprettystarsisalargewasteoftimeanddiscouragesthemaintenanceofinlinecomments.", 5. wiki:BigBlocksOfAsterisks,"Codecraft"([Link] 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"([Link] Aladdin'sCcodingguidelines([Link] C/C++ProgrammingStyles([Link] CProgrammingTutorial([Link]
Errorhandling
Cdoesnotprovidedirectsupportforerrorhandling(alsoknownasexceptionhandling).Byconvention,theprogrammerisexpectedtopreventerrorsfromoccurringinthefirstplace,[Link],1andNULLare usedinseveralfunctionssuchassocket()(Unixsocketprogramming)ormalloc()[Link],a Cprogrammerusuallytriestologtheerrorand"gracefully"terminatetheprogram. Thereisanexternalvariablecalled"errno",accessiblebytheprogramsafterincluding<errno.h>thatfilecomesfromthedefinitionofthepossibleerrorsthatcanoccurinsomeOperatingSystems([Link],thedefinitionisininclude/asm generic/errno.h)[Link]'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* /
[Link]/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* / }
[Link],[Link],aNULL pointerreturnedfrommallocsignalsanerrorinallocation,[Link],theprogrammighttrytohandletheerrorandtrytorecoverfromthefailedmemoryallocation.
Preventingdividebyzeroerrors
[Link],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,[Link],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,[Link]([Link], interrupt,andsoon.)However,thesesignalsarenotmeanttobeusedasameansoferrorcatchingtheyusuallyindicateacriticaleventthatwillinterferewithnormalprogramflow. Tohandlesignals,aprogramneedstousethe s i g n a l . h [Link],andthesignal()[Link](e.g. adivisionbyzero)[Link]. 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 ) ;
[Link]/wiki/C_Programming/Print_version
14/118
10/24/13
r e t u r nE X I T _ F A I L U R E ; } p u t s ( " E x i t i n g . " ) ; r e t u r n0 ; }
setjmp
[Link],andisvalidaslongasthefunctioncontainingsetjmp()doesn't [Link].
# 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. [Link],ifyouhaveavariable ithatis initialized(setequal)to4,thenitfollowsthat i+1willequal 5. SinceCisarelativelylowlevelprogramminglanguage,[Link] [Link] whichaCprogramshowsthenumberofvariablesitneeds,whattheyaregoingtobenamed,andhowmuchmemorytheywillneed. WithintheCprogramminglanguage,whenmanagingandworkingwithvariables,itisimportanttoknowthe typeofvariablesandthe [Link],theseaspectsofitsworkingcanbehardware specificthatis,howthelanguageismadetoworkononetypeofmachinecanbedifferentfromhowitismadetoworkonanother. AllvariablesinCare [Link],everyvariabledeclaredmustbeassignedasacertaintypeofvariable.
Declaring,Initializing,andAssigningVariables
Hereisanexampleofdeclaringaninteger,whichwe'vecalled s o m e _ n u m b e r .(Notethesemicolonattheendofthelinethatishowyourcompilerseparatesoneprogram statement fromanother.)
i n ts o m e _ n u m b e r ;
Wecanalsodeclare andassignsomecontenttoavariableatthesametime.
i n ts o m e _ n u m b e r = 3 ;
[Link]/wiki/C_Programming/Print_version
15/118
10/24/13
Afterdeclaringvariables,youcanassignavaluetoavariablelateronusingastatementlikethis:
s o m e _ n u m b e r = 3 ;
Youcanalsoassignavariablethevalueofanothervariable,likeso:
a n u m b e r=a n o t h e r n u m b e r ;
Orassignmultiplevariablesthesamevaluewithonestatement:
a n u m b e r=a n o t h e r n u m b e r=y e t a n o t h e r n u m b e r=3 ;
NamingVariables
VariablenamesinCaremadeupofletters(upperandlowercase)[Link]("_")[Link](suchasPerlandsomeBASICdialects),Cdoesnotuseany specialprefixcharactersonvariablenames. Someexamplesofvalid(butnotverydescriptive)Cvariablenames:
f o o B a r B A Z f o o _ b a r _ f o o 4 2 _ Q u U x
SomeexamplesofinvalidCvariablenames:
2 f o o m yf o o $ f o o w h i l e ( m u s tn o tb e g i nw i t had i g i t ) ( s p a c e sn o ta l l o w e di nn a m e s ) ( $n o ta l l o w e d-o n l yl e t t e r s ,d i g i t s ,a n d_ ) ( l a n g u a g ek e y w o r d sc a n n o tb eu s e da sn a m e s )
Literals
Anytimewithinaprograminwhichyouspecifyavalueexplicitlyinsteadofreferringtoavariableorsomeotherformofdata,thatvalueisreferredtoasa literal .Intheinitializationexampleabove,[Link] theirtype(moreonthatsoon),oronecanusehexadecimal(hex)notationtodirectlyinsertdataintoavariableregardlessofitstype. [citationneeded]Hexnumbersarealwaysprecededwith [Link],though,youprobablyshouldn'tbetooconcernedwith hex.
TheFourBasicDataTypes
[Link] 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 [Link]:
i n tn u m b e r O f S t u d e n t s ,i ,j = 5 ;
[Link]/wiki/C_Programming/Print_version
16/118
10/24/13
Inthisdeclarationwedeclare3variables,numberOfStudents,iandj,jhereisassignedtheliteral5.
Thec h a r type
The c h a r [Link] i n t ([Link]),[Link] C H A R _ B I T whichspecifiesthenumberof bitsinachar(byte).[Link] c h a r ismostoftenusedtostorecharacterdata,[Link],butit'sbestnotto knoworcareaboutthatunlesstheactualvaluesareimportant. Examplesofcharacterliteralsare'a','b','1',etc.,aswellassomespecialcharacterssuchas'\ 0 '(thenullcharacter)and'\ n '(newline,recall"Hello,World").Notethatthe c h a r valuemustbeenclosedwithinsinglequotations. Whenweinitializeacharactervariable,[Link],theotherwayis badprogrammingpractice. Thefirstwayistowrite
c h a rl e t t e r 1=' a ' ;
Thisisconsideredbysometobeextremely badpractice,ifweareusingittostoreacharacter,notasmallnumber,inthatifsomeonereadsyourcode,mostreadersareforcedtolookupwhatcharactercorrespondswiththenumber97intheencoding [Link], l e t t e r 1 and l e t t e r 2 storeboththesamethingtheletter'a',butthefirstmethodisclearer,easiertodebug,andmuchmorestraightforward. Oneimportantthingtomentionisthatcharactersfornumeralsarerepresenteddifferentlyfromtheircorrespondingnumber,i.e.'1'[Link],anysingleentrythatisenclosedwithin'singlequotes'. Thereisonemorekindofliteralthatneedstobeexplainedinconnectionwithchars:the stringliteral .Astringisaseriesofcharacters,[Link]("",not'').Anexampleofastringliteral isthe"Hello,World!\n"inthe"Hello,World"example. Thestringliteralisassignedtoacharacter array,[Link]:
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 [Link],[Link],itisusedwhenlessprecisionthanadoubleprovidesisrequired. f l o a t literalsmustbesuffixedwithForf,otherwisetheywillbeinterpretedas
Thed o u b l e type
The d o u b l e and f l o a t [Link] f l o a t typeallowsyoutostoresingleprecisionfloatingpointnumbers,whilethe d o u b l e keywordallowsyoutostoredoubleprecisionfloatingpointnumbersrealnumbers,inotherwords,bothintegerandnon [Link],[Link] d o u b l e literalsare3.1415926535897932,4.0,6.022e+23(scientificnotation).Ifyouuse4insteadof4.0,the4willbeinterpretedasan i n t . [Link],[Link],withmemory morefreelyavailable,[Link],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 )
[Link]/wiki/C_Programming/Print_version
17/118
10/24/13
s i z e o f ( c h a r )
alwaysreturns1.
Datatypemodifiers
Onecanalterthedatastorageofanydatatypebyprecedingitwithcertainmodifiers.
l o n g and s h o r t [Link] i n t keywordneednotfollowthe s h o r t and l o n g [Link].A s h o r t canbeusedwherethevaluesfallwithinalesser
rangethanthatofan i n t ,typically32768to32767.A l o n g [Link] 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 [Link] l o n gl o n g whichistypicallyan8byteinteger. Inallofthetypesdescribedabove,onebitisusedtoindicatethesign(positiveornegative)[Link],youmayusethe u n s i g n e d modifiertousethatonebitforstoringotherdata,effectively [Link] 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,[Link]. Whiletheideaofavariablethatneverchangesmaynotseemuseful,therearegoodreasonstouse c o n s t .Foronething,[Link],ifyouneed thevalueofinyourcalculations,youcandeclareaconstvariableof p i ,soaprogramoranotherfunctionwrittenbysomeoneelsecannotchangethevalueof p i . NotethataStandardconformingcompilermustissueawarningifanattemptismadetochangea c o n s t variablebutafterdoingsothecompilerisfreetoignorethe c o n s t qualifier.
Magicnumbers
WhenyouwriteCprograms,[Link],[Link] decidestorepresentthecostofacanofcorn,currently99cents,[Link],[Link] isnotthatbigofaproblem,consideringthe"globalfindreplace"functionofmanytexteditors,consideranotherproblem:[Link],youhavetolookateveryoccurrenceofthe number99. [Link],thoughonemethodcanbeusefulinonecircumstance,overanother.
Usingthec o n s t keyword
The c o n s t keywordhelpseradicate [Link] c o n s tc o r n atthebeginningofablock,aprogrammercansimplychangethatconstandnothavetoworryaboutsettingthevalueelsewhere. [Link] c o n s t ,[Link],[Link]...
# d e f i n e
whenyouwantto,forexample,printthepriceofcorn,youusetheword P R I C E _ O F _ C O R N insteadofthenumber0.99thepreprocessorwillreplaceallinstancesof P R I C E _ O F _ C O R N with0.99,whichthecompilerwillinterpretastheliteral d o u b l e [Link] 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 [Link],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 [Link],replacingthetext everywhere(ineffect,disregardingscope),whichcouldbeadvantageousinsome circumstances,butcanbethesourceofproblematicbugs. Youwillseefurtherinstancesofthe # d e f i n e [Link] # d e f i n e dwordsinallcapitals,soaprogrammerwillknowthatthisisnotavariablethatyouhavedeclaredbuta # d e f i n e [Link] preprocessordirectivesuchas # d e f i n e withasemicoloninfact,somecompilersmaywarnyouaboutunnecessarytokensinyourcodeifyoudo.
Scope
[Link]/wiki/C_Programming/Print_version 18/118
10/24/13
OtherModifiers
Includedhere,forcompleteness,[Link], staticand externmaybeuseful. volatileismoreofinteresttoadvancedprogrammers. registerand autoarelargelydeprecatedandare generallynotofinteresttoeitherbeginningoradvancedprogrammers.
static
s t a t i c [Link].
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
[Link]/wiki/C_Programming/Print_version
19/118
10/24/13
extern
volatile
v o l a t i l e [Link]
auto
a u t o isamodifierwhichspecifiesan"automatic"[Link]'vebeendoingallalongwhenyoudeclareavariable,you'reright:all
register
r e g i s t e r isahinttothecompilertoattempttooptimizethestorageofthegivenvariablebystoringitinaregisterofthecomputer'[Link],[Link]
Concepts
Variables Types DataStructures Arrays
Inthissection
Cvariables Ctypes Carrays
SimpleInputandOutput
Whenyoutaketimetoconsiderit,[Link],[Link] theycandotasks,sodocomputers.
[Link]/wiki/C_Programming/Print_version
20/118
10/24/13
Outputusingprintf()
Recallfromthebeginningofthistextthedemonstrationprogramduplicatedbelow:
# i n c l u d e< s t d i o . h > i n tm a i n ( v o i d ) { p r i n t f ( " H e l l o ,w o r l d ! \ n " ) ; r e t u r n0 ; }
Ifyoucompileandrunthisprogram,youwillseethesentencebelowshowuponyourscreen:
H e l l o ,w o r l d !
Thisamazingaccomplishmentwasachievedbyusingthe function p r i n t f ( ) .Afunctionislikea"blackbox"[Link],butwewillcoverthatlater. Youhaveseenthattouse p r i n t f ( ) oneputstext,surroundedbyquotes,[Link] literalstring(orjusta string),andwecallthatstringan argument toprintf. Asanoteofexplanation,itissometimesconvenienttoincludetheopenandclosingparenthesesafterafunctionnametoremindusthatitis,indeed,[Link],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,[Link]'tknowwhat19+[Link]'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 ) {
[Link]/wiki/C_Programming/Print_version
21/118
10/24/13
p r i n t f ( " 1 9 + 3 1i s " ) ;
Theplaceholder%dliterally"holdstheplace"fortheactualnumberthatistheresultofadding19to31. Theseplaceholdersarecalled [Link] p r i n t f .Ifwehaveafloatingpointnumber,wecanuse % f toprintoutafloatingpointnumber,[Link]: %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:[Link]?
ortobeabitmoreclear,[Link]
# i n c l u d e< s t d i o . h > i n tm a i n ( v o i d ) { p r i n t f ( "1 9 0 5 \ n " ) ; p r i n t f ( " 3 1 2+ \ n " ) ; p r i n t f ( " \ n " ) ; p r i n t f ( " % d " ,1 9 0 5 + 3 1 2 ) ; r e t u r n0 ; }
Otheroutputmethods
puts()
Theputs()[Link]()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 .
[Link]/wiki/C_Programming/Print_version
22/118
10/24/13
followedbythenewlinecharacter(asdiscussedabove).(The p u t s functionappendsanewlinecharactertoitsoutput.)
# i n c l u d e < s t d i o . h > f ( i n ti , i n tj , i n tk ) { p r i n t f ( " % d % d % d " , i , j , k ) ; } m a i n ( ) { i n tx = 1 , y = 2 , z = 3 ; f ( x + y , y = x + z , z = x + y ) ; }
Inputusingscanf()
Thescanf()functionistheinputmethodequivalenttotheprintf()[Link],thescanf formatstringholdsasingle [Link] placeholdersareexactlythesameastheprintf()function%dforints,%fforfloats,and%lffordoubles. Thereis,however,onevariationtoscanf()ascomparedtoprintf().Thescanf()[Link] pointersarepossiblehere,thisisaconceptthatwon'tbeapproached [Link],thesimpletechniqueistousethe addressof operator, &.Fornowitmaybebesttoconsiderthis"magic"beforewediscusspointers. Atypicalapplicationmightbelikethis:
# i n c l u d e" s t d i o . h " i n tm a i n ( v o i d ) { i n ta ; p r i n t f ( " P l e a s ei n p u ta ni n t e g e rv a l u e :" ) ; s c a n f ( " % d " ,& a ) ; p r i n t f ( " Y o ue n t e r e d :% d \ n " ,a ) ; r e t u r n0 ; }
Thecorrectusagewouldbe:
s c a n f ( " % s " ,a ) ;
Links
Backtocontents:BeginningC
Simplemath
OperatorsandAssignments
[Link]:
Primaryexpressions
Anidentifierisaprimaryexpression,providedthatithasbeendeclaredasdesignatinganobject(inwhichcaseitisanlvalue[avaluethatcanbeusedastheleftsideofanassignmentexpression])orafunction(inwhichcaseitisafunctiondesignator). [Link].
[Link]/wiki/C_Programming/Print_version
23/118
10/24/13
Astringliteralisaprimaryexpression.
[Link].
Postfixoperators
First,[Link]: Apostfixexpressionfollowedbyaleftsquarebracket([ ),anexpression,andarightsquarebracket(] )[Link]"pointertoobject type"andtheothershallhavean integertypetheresulttypeis [Link]. Apostfixexpressionfollowedbyparenthesesoranoptionalparenthesizedargumentlistindicatesaninvocationofthefunctioncalloperator. Apostfixexpressionfollowedbyadot(. )followedbyanidentifierselectsamemberfromastructureorunionapostfixexpressionfollowedbyanarrow(> )followedbyanidentifierselectsamemberfromastructureorunionwhoispointedtobythe pointeronthelefthandsideoftheexpression. Apostfixexpressionfollowedbytheincrementordecrementoperators(+ + or )[Link] beforetheincrementor decrement.
Unaryexpressions
First,[Link]: [Link] aftertheincrementordecrement. Thefollowingoperatorsfollowedbyacastexpressionareunaryexpressions:
O p e r a t o r = = = = = = = = & * + ! ~ M e a n i n g = = = = = = = A d d r e s s o f ;v a l u ei st h el o c a t i o no ft h eo p e r a n d C o n t e n t s o f ;v a l u ei sw h a ti ss t o r e da tt h el o c a t i o n N e g a t i o n V a l u e o fo p e r a t o r L o g i c a ln e g a t i o n(( ! E )i se q u i v a l e n tt o( 0 = = E )) B i t w i s ec o m p l e m e n t
Castoperators
Acastexpressionisaunaryexpression. [Link],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,[Link]:+(addition),(subtraction),*(multiplication),/(division),and%(modulus)Youlikelyknowallofthemfromyourmathclassesexcept,perhaps,[Link] remainder ofadivision(e.g.5%2=1). Caremustbetakenwiththemodulus,becauseit'snottheequivalentofthemathematicalmodulus:(5)%2isnot1,[Link],andthedivisionofanegativeintegerbyapositiveintegerwillroundtowardszero insteadofroundingdown(e.g.(5)/3=1insteadof2). Thereisnoinlineoperatortodothepower(e.g.5^2is not25,and5**2isanerror),butthereisapowerfunction. [Link](2+3)*2=10while2+3*2=[Link].
# i n c l u d e< s t d i o . h >
[Link]/wiki/C_Programming/Print_version
24/118
10/24/13
i n tm a i n ( ) { i n ti=0 ,j=0 ; / *w h i l eii sl e s st h a n5A N Dji sl e s st h a n5 ,l o o p* / w h i l e (( i<5 )& &( j<5 )) { / *p o s t f i xi n c r e m e n t ,i + + * t h ev a l u eo fii sr e a da n dt h e ni n c r e m e n t e d * / p r i n t f ( " i :% d \ t " ,i + + ) ; / * *p r e f i xi n c r e m e n t ,+ + j * t h ev a l u eo fji si n c r e m e n t e da n dt h e nr e a d * / p r i n t f ( " j :% d \ n " ,+ + j ) ; } p r i n t f ( " A tt h ee n dt h e yh a v eb o t he q u a lv a l u e s : \ n i :% d \ t j :% d \ n " ,i ,j ) ; r e t u r n0 ; }
willdisplaythefollowing:
i :0 j :1 i :1 j :2 i :2 j :3 i :3 j :4 i :4 j :5 A tt h ee n dt h e yh a v eb o t he q u a lv a l u e s : i :5 j :5
shiftandrotate
ShiftfunctionsareoftenusedinlowlevelI/[Link],shiftscanbeusedinplaceofdivisionormultiplicationbyapowerof [Link]/[Link],mostCcompilerscompileshiftandrotateoperatorstoasingleassembly languageinstructionseeX86Assembly/ShiftandRotate. shiftleft The < < operatorshiftsthebinaryrepresentationtotheleft,[Link]. unsignedshiftright Theunsignedshiftrightoperator,[Link],[Link] > > operatorisequivalenttodivisionbyapowerof twoforunsignedintegers. signedshiftright Thesignedshiftrightoperator,[Link],droppingtheleastsignificantbit,[Link] > > operatorisnotequivalent todivisionforsignedintegers. InC,thebehaviorofthe > > [Link],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 ) ) ;
[Link]/wiki/C_Programming/Print_version
25/118
10/24/13
rotateleft Mostcompilersrecognizethisidiom:
u n s i g n e di n tx ; u n s i g n e di n ty ; / *. . .* / y=( x< <s h i f t )|( x> >( 3 2-s h i f t ) ) ;
andcompileittoasingle32bitrotateinstruction. Onsomesystems,thismaybe"#define"edasamacroordefinedasaninlinefunctioncalledsomethinglike"leftrotate32"or"rotl32"inaheaderfilelike"bitops.h".
Relationalandequalityoperators
Therelationalbinaryoperators < (lessthan), > (greaterthan), < = (lessthanorequal),and > = (greaterthanorequal)operatorsreturnavalueof1iftheresultoftheoperationistrue,0iffalse. Theequalitybinaryoperators = = (equals)and ! = (notequals)operatorsaresimilartotherelationaloperatorsexceptthattheirprecedenceislower.
Bitwiseoperators
Thebitwiseoperatorsare & (and), ^ (exclusiveor)and | (inclusiveor).The & operatorhashigherprecedencethan ^ ,whichhashigherprecedencethan | .
Logicaloperators
Thelogicaloperatorsare & & (and),and | | (or).[Link],thesecondisignored.
& & isusedtoevaluateexpressionslefttoright,andreturnsa1if bothstatementsaretrue.
Here,the&&operatorcheckstheleftmostexpression,thentheexpressiontoit'[Link],the&&operatorreturnstrue,andthecodeblockisexecuted.
i f ( x= =5& &y= =5 ){ . . . }
The&&operatorchecksinthesamewayasbefore,[Link]&&operatorstopsevaluatingassoonasitfindsastatementtobefalse,andreturnsafalse.
| | isusedtoevaluateexpressionslefttoright,andreturnsa1if eitheroftheexpressionsaretrue.
Conditionaloperators
Theternary ? : [Link] ( x?y:z ) hasthevalueof y if x isnonzero, z otherwise. Example:
[Link]/wiki/C_Programming/Print_version
26/118
10/24/13
Assignmentoperators
Theassignmentoperatorsare = , * = , / = , % = , + = , = , < < = , > > = , & = , ^ = ,and | = .The = operatorstoresthevalueoftherightoperandintothelocationdeterminedbytheleftoperand,whichmustbeanlvalue Fortheothers, xo p =y isshorthandfor x=xo p( y ) .Hence,thefollowingexpressionsarethesame:
1 .x+ =y 2 .x=y 3 .x* =y 4 .x/ =y 5 .x% =y x=x + y x=x y x=x * y x=x / y x=x % y
Commaoperator
[Link] x ,y willevaluateboth x and y ,butprovidesthevalueof y . Thisoperatorisusefulforincludingmultipleactionsinonestatement([Link]). Herearesomesmallexamplesofthecommaoperator:
i n ti ,x ; / *d e c l a r e st w oi n t s ,ia n dx ,i no n es t a t e m e n t* /
1. Severalprogrammersrecommend"[Link]."[1]([Link] ([Link] tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5]([Link] 3. [[Link] 4. "CodingConventionsforC++andJava"([Link] Thisdeliberatechoicewasmadebecausealigningthoseprettystarsisalargewasteoftimeanddiscouragesthemaintenanceofinlinecomments.", 5. wiki:BigBlocksOfAsterisks,"Codecraft"([Link] 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"([Link]
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 [Link] thesemathfunctions,[Link](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 [Link][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* /
[Link]/wiki/C_Programming/Print_version
27/118
10/24/13
# i n c l u d e< m a t h . h > f l o a ta t a n f ( f l o a tx ) ;/ *C 9 9* / f l o a ta t a n 2 f ( f l o a ty ,f l o a tx ) ;/ *C 9 9* / d o u b l ea t a n ( d o u b l ex ) ; d o u b l ea t a n 2 ( d o u b l ey ,d o u b l ex ) ; l o n gd o u b l ea t a n l ( l o n gd o u b l ex ) ;/ *C 9 9* / l o n gd o u b l ea t a n 2 l ( l o n gd o u b l ey ,l o n gd o u b l ex ) ;/ *C 9 9* /
Hyperbolicfunctions
The c o s h , s i n h and t a n h functionscomputethehyperboliccosine,thehyperbolicsine,[Link],arangeerroroccursifthemagnitudeoftheargumentistoolarge. The a c o s h functionscomputetheinversehyperboliccosineoftheargument.Adomainerroroccursforargumentslessthan1. The a s i n h functionscomputetheinversehyperbolicsineoftheargument. The a t a n h [Link][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,[Link] 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* /
[Link]/wiki/C_Programming/Print_version
28/118
10/24/13
Thef r e x p ,l d e x p ,m o d f ,s c a l b n ,ands c a l b l n functions
The f r e x p functionsbreaktheargumentfloatingpointnumber v a l u e intothosetwoparts,[Link],itstorestheexponentinthe i n t objectpointedtoby e x ,[Link],thevalue [Link] v a l u e iszero,bothpartsoftheresultarezero. The l d e x p [Link],[Link]. The m o d f functionsbreaktheargument v a l u e intointegerandfractionparts,[Link] * i p t r [Link] * 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]([Link]
# 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* /
[Link]/wiki/C_Programming/Print_version
29/118
10/24/13
i n ti l o g b ( d o u b l ex ) ;/ *C 9 9* / i n td o u b l ei l o g b l ( l o n gd o u b l ex ) ;/ *C 9 9* / f l o a tl o g b f ( f l o a tx ) ;/ *C 9 9* / d o u b l el o g b ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l el o g b l ( l o n gd o u b l ex ) ;/ *C 9 9* /
Powerfunctions
Thep o w functions
The p o w functionscompute x raisedtothepower y [Link] x isnegativeand y [Link] 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 [Link].
# 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* /
[Link]/wiki/C_Programming/Print_version
30/118
10/24/13
Thef m o d functions
The f m o d functionscomputethefloatingpointremainderof x / y andreturnthevalue x i* y ,forsomeinteger isuchthat,if y isnonzero,theresulthasthesamesignas x andmagnitudelessthanthemagnitudeof y .If y iszero,whetheradomainerror occursorthe f m o d functionsreturnzeroisimplementationdefined.
# i n c l u d e< m a t h . h > f l o a tf m o d f ( f l o a tx ,f l o a ty ) ;/ *C 9 9* / d o u b l ef m o d ( d o u b l ex ,d o u b l ey ) ; l o n gd o u b l ef m o d l ( l o n gd o u b l ex ,l o n gd o u b l ey ) ;/ *C 9 9* /
Thet r u n c functions
The t r u n c functionsroundtheirargumenttotheintegervalueinfloatingpointformatthatisnearestbutnolargerinmagnitudethantheargument.
# i n c l u d e< m a t h . h > f l o a tt r u n c f ( f l o a tx ) ;/ *C 9 9* / d o u b l et r u n c ( d o u b l ex ) ;/ *C 9 9* / l o n gd o u b l et r u n c l ( l o n gd o u b l ex ) ;/ *C 9 9* /
Ther e m a i n d e r functions
The r e m a i n d e r functionscomputetheremainder x REM y [Link],"When y0,theremainder r= xREM yisdefinedregardlessoftheroundingmodebythemathematicalreduction r= x ny,where nistheinteger nearesttheexactvalueof x/ ywhenever|n x/ y|=,then [Link],[Link] 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
[Link]/wiki/C_Programming/Print_version
31/118
10/24/13
Errorandgammafunctions
The e r f functionscomputetheerrorfunctionoftheargument(2/() 0x et dt)the e r f c functionscomputethecomplimentaryerrorfunctionoftheargument(thatis,1erfx).Forthe e r f c functions,arangeerrormayoccuriftheargumentistoolarge. The l g a m m a functionscomputethenaturallogarithmoftheabsolutevalueofthegammaoftheargument(thatis,loge|(x)|).Arangeerrormayoccuriftheargumentisanegativeintegerorzero. The t g a m m a functionscomputethegammaoftheargument(thatis,(x)).[Link].
# 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"[Link]."[1]([Link] ([Link] tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5]([Link] 3. [[Link] 4. "CodingConventionsforC++andJava"([Link] Thisdeliberatechoicewasmadebecausealigningthoseprettystarsisalargewasteoftimeanddiscouragesthemaintenanceofinlinecomments.", 5. wiki:BigBlocksOfAsterisks,"Codecraft"([Link] 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"([Link]
Control
[Link],itisnecessarytounderstandhowonecanalterthestepstakenbyaprogramduetouserinputorotherconditions,howsome stepscanbeexecutedmanytimeswithfewlinesofcode,[Link]. Fromthispointforward,itisnecessarytounderstandwhatisusuallymeantbytheword [Link],thebeginningofablockofcodeisdenotedwith{(left curly),andtheendofablockisdenotedwith}.[Link],asin{}.[Link].
Conditionals
[Link],instinctualorotherwise, [Link],whendrivingacarandapproachingatrafficlight,onedoesnotthink,"Iwillcontinuedrivingthroughtheintersection."Rather,onethinks,"Iwillstopifthelightisred,goifthelightisgreen,andifyellowgoonlyifIam travelingatacertainspeedacertaindistancefromtheintersection."ThesekindsofprocessescanbesimulatedinCusingconditionals. [Link],withconditionalexpressionsandSwitchCase statementstypicallyusedasmoreshorthandedmethods. Beforeonecanunderstandconditionalstatements,[Link].Thevalue0(zero)representsfalse,and [Link] particularvaluetorepresenttrueandthencomparevaluesagainstit,soonerorlateryourcodewillfailwhenyourassumedvalue(often1)[Link] usageof#definetomakea"TRUE"value. [4] BecauselogicisarithmeticinC,[Link],thereareanumberofoperatorsthataretypicallyassociatedwithlogic:
[Link]/wiki/C_Programming/Print_version
32/118
10/24/13
RelationalandEquivalenceExpressions:
a<b 1if aislessthan b,0otherwise. a>b 1if aisgreaterthan b,0otherwise. a<=b 1if aislessthanorequalto b,0otherwise. a>=b 1if aisgreaterthanorequalto b,0otherwise. a==b 1if aisequalto b,0otherwise. a!=b 1if aisnotequalto b,0otherwise
Newprogrammersshouldtakespecialnoteofthefactthatthe"equalto"operatoris==,not=.Thisisthecauseofnumerouscodingmistakesandisoftenadifficulttofindbug,astheexpression ( a=b ) sets a equalto b andsubsequentlyevaluatesto b buttheexpression ( a= =b ) ,whichisusuallyintended,checksif a isequalto b .Itneedstobepointedoutthat,ifyouconfuse=with==,[Link] i f(c=2 0 ){ } is consideredperfectlyvalidbythelanguage,butwillalwaysassign20to c [Link](inmany,notallcases)[Link],if==got misspelledwith=. [Link]:
i f( f o o ( ) ){ / / d os o m e t h i n g }
and
i f( f o o ( )! =0 ){ / / d os o m e t h i n g }
Here, s t r s t r [Link] T R U E [Link] > =0 . [Link],anexpression m y M i n<v a l u e<m y M a x [Link],thiswouldtestwhetherornot value isbetween myMinand [Link],whathappensisthat valueisfirstcomparedwith [Link]:
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,[Link] 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.
[Link]/wiki/C_Programming/Print_version
33/118
10/24/13
!a when aistrue,theresultis0,when ais0,theresultis1. Here'[Link]:
e=( ( a& &b )| |( c>d ) ) ;
eissetequalto1ifaandbarenonzero,[Link],eissetto0. [Link],onceitisabletodeterminethetruthofalogicalexpression,[Link]:
i n tm y A r r a y [ 1 2 ] ; . . . . i f(i<1 2& &m y A r r a y [ i ]>3 ){ . . . .
doThat()isnevercalledifdoThis()returnsanonzero(true)value.
BitwiseBooleanExpressions
[Link](oneofthetypesusedforintegers).Thesixbitwiseoperatorsare&(AND),|(OR),^(exclusiveOR,commonlycalledXOR),~(NOT,whichchanges1to0and0 to1),<<(shiftleft),and>>(shiftright).[Link] equivalenceoperatorsitisoftenrequiredtoparenthesizeexpressionsinvolvingbitwiseoperators. Forthissection,recallthatanumberstartingwith 0xishexadecimal,orhexforshort.Unlikethenormaldecimalsystemusingpowersof10anddigits0123456789,[Link] 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
[Link]:
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* / }
[Link]/wiki/C_Programming/Print_version
34/118
10/24/13
Thefirstblockofcodeexecutesiftheconditioninparenthesesdirectlyafterthe if evaluatestononzero(true)otherwise,thesecondblockexecutes. The [Link],leaveitout. Also,keepinmindthatan if candirectlyfollowan [Link],[Link] constructdescribedlater. Twoothergeneralsyntaxnotesneedtobemadethatyouwillalsoseeinothercontrolconstructs:First,notethatthereisnosemicolonafter if or [Link],buttheblock(codeenclosedin{and})[Link],ifyouonly intendtoexecuteonestatementasaresultofan if or else,[Link],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 ; }
[Link],ifyourconditionalsarenotmutuallyexclusive, [Link](e.g.:youresetthelesserofaandbto0 afterthecomparison)duringoneoftheblocks?Youcouldendupwithmultiple if statementsbeinginvoked,[Link],evaluating if [Link] elsetohandlethesesituations,inthecaseabove assuming(a>b)isnonzero(true),theprogramissparedtheexpenseofevaluatingadditional if [Link] elseclauseforallcasesinwhichaconditionalwillnotevaluatetononzero(true). Theconditionalexpression [Link]:
( / *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 )* / )
[Link](true),theoverallconditionalexpressionevaluatestotheexpressionplacedbetweenthe?and:,otherwise,itevaluatestotheexpressionafterthe:.Therefore,theaboveexample(changingitsfunction slightlysuchthatcissettobwhenaandbareequal)becomes:
c=( a>b )?a:b ;
[Link]'[Link],contrarytoacommon beginnerbelief,[Link],thereisnosuchcorrelation.
TheSwitchCasestatement
Sayyouwriteaprogramwheretheuserinputsanumber15(correspondingtostudentgrades,A(representedas1)D(4)andF(5)),storesitinavariable [Link] 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,[Link],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* /
[Link]/wiki/C_Programming/Print_version
35/118
10/24/13
/ *i n s e r ta d d i t i o n a lc a s e sa sn e e d e d* / d e f a u l t : / *m o r ec o d e* / }
TheSwitchCaseconstructtakesavariable,usuallyanintoranenum,placedafter switch,andcomparesittothevaluefollowingthe [Link] case,theconstruct"activates",orbeginsexecutingthe [Link]"activated",therewillbenofurtherevaluationof cases. SwitchCaseissyntactically"weird"inthatnobracesarerequiredforcodeassociatedwitha case. Veryimportant:Typically,[Link],[Link] ifthebreakstatementisomitted,programexecutioncontinueswiththefirstlineofthenextcase,[Link] [Link],acommentshouldbeplacedattheendoftheblockofstatementsindicating [Link]'break'tobeanerror,andinadvertently'correct'[Link]'sanexample:
s w i t c h(s o m e V a r i a b l e){ c a s e1 : p r i n t f ( " T h i sc o d eh a n d l e sc a s e1 \ n " ) ; b r e a k ; c a s e2 : p r i n t f ( " T h i sp r i n t sw h e ns o m e V a r i a b l ei s2 ,a l o n gw i t h . . . \ n " ) ; / *F A L LT H R O U G H* / c a s e3 : p r i n t f ( " T h i sp r i n t sw h e ns o m e V a r i a b l ei se i t h e r2o r3 . \ n ") ; b r e a k ; }
Asetofstatementstoexecutecanbegroupedwithmorethanonevalueofthevariableasinthefollowingexample.(thefallthroughcommentisnotnecessaryherebecausetheintendedbehaviorisobvious)
s w i t c h( s o m e t h i n g ){ c a s e2 : c a s e3 : c a s e4 : / *s o m es t a t e m e n t st oe x e c u t ef o r2 ,3o r4* / b r e a k ; c a s e1 : d e f a u l t : / *s o m es t a t e m e n t st oe x e c u t ef o r1o ro t h e rt h a n2 , 3 , a n d4* / b r e a k ; }
SwitchCaseconstructsareparticularlyusefulwhenusedinconjunctionwithuserdefined [Link],whichmaybehelpfulforavoidingbugs.
Loops
Oftenincomputerprogramming,[Link],notto [Link],[Link],"Iwasheddishesallnight long."Heisnotlikelytorespond,"Iwashedadish,thenwashedadish,thenwashedadish,then...".Theconstructsthatenablecomputerstoperformcertainrepetitivetasksarecalledloops.
Whileloops
[Link](true).Forexample,ifyoutrythefollowing,[Link] conditionsforexitingtheloopwillneverbecometrueiscalledaninfiniteloop.
i n ta = 1 ;
[Link]/wiki/C_Programming/Print_version
36/118
10/24/13
w h i l e ( 4 2 ){ a=a * 2 ; }
Hereisanotherexampleofawhileloop.Itprintsoutallthepowersoftwolessthan100.
i n ta = 1 ; w h i l e ( a < 1 0 0 ){ p r i n t f ( " ai s% d\ n " , a ) ; a=a * 2 ; }
Inthisexample,thecomputerprintsthevalueofaasusual,andprintsanoticethataisnot64(unlessitwasskippedbythecontinuestatement). SimilartoIfabove,bracesfortheblockofcodeassociatedwithaWhileloopcanbeomittedifthecodeconsistsofonlyonestatement,forexample:
i n ta = 1 ; w h i l e ( a<1 0 0 )a=a * 2 ;
Thisexecutesthecodeinthewhileloop5times,withihavingvaluesthatrangefrom4downto0(insidetheloop).Conveniently,thesearethevaluesneededtoaccesseveryitemofanarraycontaining5elements.
Forloops
Forloopsgenerallylooksomethinglikethis:
f o r ( i n i t i a l i z a t i o n ;t e s t ;i n c r e m e n t ){ / *c o d e* / }
The initializationstatementisexecutedexactlyoncebeforethefirstevaluationofthe test [Link],itisusedtoassignaninitialvaluetosomevariable,[Link] initializationstatementcanalsobeusedto declareandinitializevariablesusedintheloop. The test expressionisevaluatedeachtimebeforethecodeinthe forloopexecutes.Ifthisexpressionevaluatesas0(false)whenitischecked([Link]),theloopisnot(re)enteredandexecutioncontinuesnormallyatthecode [Link](true),thecodewithinthebracesoftheloopisexecuted. Aftereachiterationoftheloop,the increment [Link],[Link], controlreturnstothetopoftheloop,wherethe test [Link] continuestatementisexecutedwithinthe forloop,theincrementstatementwouldbethenextoneexecuted. [Link],[Link],processingeachitemat atime.
[Link]/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 ; }
[Link].Inthefollowingcaseitstartsfrom1.
f o r ( i x=1 ;i x< =1 0 ;i x + + ){ p r i n t f ( " % d" ,i x ) ; }
whichwillprint
1234567891 0
whichyields
54321
Here'sanexamplewherethetestconditionissimplyavariable.Ifthevariablehasavalueof0orNULL,theloopexits,otherwisethestatementsinthebodyoftheloopareexecuted.
f o r( t=l i s t _ h e a d ;t ;t=N e x t I t e m ( t )){ / * b o d yo fl o o p* / }
AWHILEloopcanbeusedtodothesamethingasaFORloop,howeveraFORloopisamorecondensedwaytoperformasetnumberofrepetitionssinceallofthenecessaryinformationisinaonelinestatement. AFORloopcanalsobegivennoconditions,forexample:
f o r ( ; ; ){ / *b l o c ko fs t a t e m e n t s* / }
[Link]. 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
[Link]/wiki/C_Programming/Print_version
38/118
10/24/13
ADOWHILEloopisapostcheckwhileloop,[Link],eveniftheconditioniszero(false),[Link]:
d o{ / *d os t u f f* / }w h i l e( c o n d i t i o n ) ;
Onelastthing:goto
[Link],[Link] colon(:)[Link],youcantype"goto label"[Link] [Link]:
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,[Link],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".[Link]:
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,[Link],unmaintainablecodewhenmoreidiomaticalternatives(suchasifelses,orfor loops)[Link],thegotoconstructdoesnotever havetobeused,buttherearecaseswhenitcanincreasereadability,avoidcodeduplication,[Link] masteringtheidiomaticsolutions,[Link],ifnotmost,Cstyleguidelines strictlyforbiduseof goto,withtheonlycommonexceptionsbeingthefollowingexamples. [Link] breakwillnotwork(itcanonlyescapeoneloop), [Link] possible,butofteninvolvesthecreationandtestingofextravariablesthatmaymaketheresultingcodefarlessreadablethanitwouldbewith [Link] gotomakesiteasytoundoactionsinanorderlyfashion,typicallytoavoidfailingtofree memorythathadbeenallocated. [Link],andnotcommonlyneeded.
Examples
[Link]/wiki/C_Programming/Print_version 39/118
10/24/13
# i n c l u d e< e r r n o . h > # i n c l u d e< s t d i o . h > # i n c l u d e< s t d l i b . h > i n tm a i n ( v o i d ) { i n ty e a r s ; p r i n t f ( " E n t e ry o u ra g ei ny e a r s:" ) ; f f l u s h ( s t d o u t ) ; e r r n o=0 ; i f ( s c a n f ( " % d " ,& y e a r s )! =1| |e r r n o ) r e t u r nE X I T _ F A I L U R E ; p r i n t f ( " Y o u ra g ei nd a y si s% d \ n " ,y e a r s*3 6 5 ) ; r e t u r n0 ; }
Furtherreading
1. Severalprogrammersrecommend"[Link]."[1]([Link] ([Link] tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5]([Link] 3. [[Link] 4. "CodingConventionsforC++andJava"([Link] Thisdeliberatechoicewasmadebecausealigningthoseprettystarsisalargewasteoftimeanddiscouragesthemaintenanceofinlinecomments.", 5. wiki:BigBlocksOfAsterisks,"Codecraft"([Link] 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"([Link]
Proceduresandfunctions
InCprogramming,allexecutablecoderesideswithina [Link]"function","subroutine", "subprogram","procedure",or"method"inC,theseareallfunctions. Afunctionisoftenexecuted(called)severaltimes,fromseveraldifferentplaces,[Link],theprogramwillbranchback(return)tothepointafterthecall. Functionsareapowerfulprogrammingtool. Asabasicexample,supposeyouarewritingcodetoprintoutthefirst5squaresofnumbers,dosomeintermediateprocessing,[Link]:
# 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 ; }
[Link]:
# 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 ;
[Link]/wiki/C_Programming/Print_version
40/118
10/24/13
}
Thisispreciselywhatfunctionsarefor.
Moreonfunctions
[Link],doessomethingwithit,thenspitsoutananswer. Notethatafunctionmaynottakeanyinputsatall,[Link],ifweweretomakeafunctionofthatloop,wemaynotneedanyinputs,andwearen'treturninganythingatall(Textoutputdoesn'tcount whenwespeakof returningwemeantosaymeaningfuldatathattheprogramcanuse). Wehavesometerminologytorefertofunctions: Afunction,callit f ,thatusesanotherfunction g,issaidto call [Link], f calls gtoprintthesquaresoftennumbers. Afunction'sinputsareknownasits arguments Afunction gthatgivessomekindofanswerbackto f issaidto [Link], greturnsthesumofitsarguments.
WritingfunctionsinC
It'[Link]'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,[Link] i n t ,x,andsquaresit,storingitinthevariablesquare_of_x.Nowthisvalueisreturned. [Link],andwearereturningthisinteger,andsowewrite i n t asthereturntype. [Link]"square",becausethat'swhatit doesitsquaresanumber. Nextisthefunction'sfirstandonlyargument,an i n t ,[Link]'s input . Inbetweenthebracesistheactualgutsofthefunction.Itdeclaresanintegervariablecalledsquare_of_xthatwillbeusedtoholdthevalueofthesquareofx.Notethatthevariablesquare_of_xcan onlybeusedwithinthisfunction,andnotoutside. We'lllearnmoreaboutthissortofthinglater,andwewillseethatthispropertyisveryuseful. Wethenassignxmultipliedbyx,orxsquared,tothevariablesquare_of_x,[Link] r e t u r n [Link],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* / }
[Link]/wiki/C_Programming/Print_version
41/118
10/24/13
p r i n t f ( " H e l l o ! \ n ' ' ' " ) ; } }
Noticethisfunctiondoesn'ttakeanyinputs,butmerelyreturnsanumbercalculatedbythisfunction. Naturally,youcancombinebothvoidreturnandvoidinargumentstogethertogetavalidfunction,also.
Recursion
Here'[Link],whichagainprintsalineandcallsitselfagain,[Link],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 ( ) ; }
[Link]++[Link].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,[Link],thecompilerwillnowcompiletoanobjectfileinawaythatpreventsthefunctionfrombeing [Link]:
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
[Link]/wiki/C_Programming/Print_version
42/118
10/24/13
i n ts q u a r e _ o f _ 1 0 ; s q u a r e _ o f _ 1 0=s q u a r e ( 1 0 ) ;
Ifafunctiondoesn'treturnanything,wecanjustsay
s a y _ h e l l o ( ) ;
sincewedon'tneedavariabletocatchitsreturnvalue.
FunctionsfromtheCStandardLibrary
WhiletheClanguagedoesn'titselfcontainfunctions,[Link],youneedtoaddan#includedirectiveatthetopoftheCfile,whichmaybeoneofthefollowing:
< c o m p l e x . h >
Thefunctionsavailableare:
< a s s e r t . h > < l i m i t s . h > < s i g n a l . h > < s t d l i b . h >
assert(int)
(constantsonly)
intraise(intsig).This void*signal(intsig,void(*func)(int))
atof(char*),atoi(char*),atol(char*) strtod(char*str,char**endptr),strtol(char*str,char**endptr),strtoul(char*str,char**endptr) rand(),srand() malloc(size_t),calloc(size_telements,size_telementSize),realloc(void*,int) free(void*) exit(int),abort() atexit(void(*func)()) getenv system qsort(void*,size_tnumber,size_tsize,int(*sortfunc)(void*,void*)) abs,labs div,ldiv
< s t r i n g . h >
< c t y p e . h >
< l o c a l e . h >
< s t d a r g . h >
structlconv*localeconv(void) char*setlocale(int,constchar*)
memcpy,memmove memchr,memcmp,memset strcat,strncat,strchr,strrchr strcmp,strncmp,strccoll strcpy,strncpy strerror strlen strspn,strcspn strpbrk strstr strtok strxfrm time.h
errno.h
stddef.h
[Link]/wiki/C_Programming/Print_version
43/118
10/24/13
fabs floor fmod frexp ldexp log,log10 modf pow sqrt
(errno)
offsetofmacro
float.h
setjmp.h fclose fopen,freopen remove rename rewind tmpfile clearerr feof,ferror fflush fgetpos,fsetpos fgetc,fputc fgets,fputs ftell,fseek
stdio.h fread,fwrite getc,putc getchar,putchar,fputchar gets,puts printf,vprintf fprintf,vfprintf sprintf,snprintf,vsprintf,vsnprintf perror scanf,vscanf fscanf,vfscanf sscanf,vsscanf setbuf,setvbuf tmpnam ungetc
(constants)
intsetjmp(jmp_bufenv) voidlongjmp(jmp_bufenv,intvalue)
printf fulllist([Link]
Variablelengthargumentlists
[Link] p r i n t f function,whichcantakeanynumberofargumentsdependingonhowtheprogrammerwantstouse it. [Link],theytypicallydefineastructuretoholdallthosethingsperhapsalinkedlist,oranarrayandcallthat functionwiththedatainthearguments. However,[Link],youmustfirstincludethestandardlibraryheader s t d a r g . h .Next,declare [Link],addasthelastargumentanellipsis("...").[Link],thefollowingfunctiondeclarationisforafunctionthatreturnstheaverageofa listofnumbers:
f l o a ta v e r a g e( i n tn _ a r g s ,. . . ) ;
[Link]/wiki/C_Programming/Print_version
44/118
10/24/13
}
Bypopping n _ a r g s integersoffofthevariablelengthargumentlist,wecanmanagetofindtheaverageofthenumbers:
# i n c l u d e< s t d a r g . h > f l o a ta v e r a g e( i n tn _ a r g s ,. . . ) { v a _ l i s tm y L i s t ; v a _ s t a r t( m y L i s t ,n _ a r g s ) ; i n tn u m b e r s A d d e d=0 ; i n ts u m=0 ; w h i l e( n u m b e r s A d d e d<n _ a r g s ){ i n tn u m b e r=v a _ a r g( m y L i s t ,i n t ) ;/ /G e tn e x tn u m b e rf r o ml i s t s u m+ =n u m b e r ; n u m b e r s A d d e d+ =1 ; } v a _ e n d( m y L i s t ) ; f l o a ta v g=( f l o a t ) ( s u m )/( f l o a t ) ( n u m b e r s A d d e d ) ;/ /F i n dt h ea v e r a g e r e t u r na v g ; }
Preprocessor
[Link] [Link]#(hash)symbol.C++compilersusethesameCpreprocessor. [5] Thepreprocessorisapartofthecompilerwhichperformspreliminaryoperations(conditionallycompilingcode,includingfilesetc...)[Link],meaningthattheoutputofthepreprocessoris stilltext.
Directives
Directivesarespecialinstructionsdirectedtothepreprocessor(preprocessordirective)ortothecompiler(compilerdirective)onhowitshouldprocesspartorallofyoursourcecodeorsetsomeflagsonthefinalobjectandareusedtomakewritingsource codeeasier(moreportableforinstance)[Link],whichiseitheraseparateprograminvokedbythecompilerorpartofthecompileritself.
#include
Chassomefeaturesaspartofthelanguageandsomeothersaspartofa standardlibrary,[Link] [Link],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 [Link] preprocessingdirectivewhichshouldlooklikethis:
# i n c l u d e< s t d i o . h >
TheabovelinecausestheCdeclarationswhichareinthe s t d i o . h [Link] headerfilecalled s t d i o . h ,locatedinasystemdependent [Link]'[Link]. The s t d i o . h headercontainsvariousdeclarationsforinput/output(I/O)usinganabstractionofI/Omechanismscalled [Link] s t d o u t whichisusedtooutputtexttothestandardoutput,whichusually displaysthetextonthecomputerscreen.
[Link]/wiki/C_Programming/Print_version
45/118
10/24/13
Ifusinganglebracketsliketheexampleabove,thepreprocessorisinstructedtosearchfortheincludefilealongthedevelopmentenvironmentpathforthestandardincludes.
# i n c l u d e" o t h e r . h "
NOTE:Youshouldcheckthedocumentationofthedevelopmentenvironmentyouareusingforanyvendorspecificimplementationsofthe # i n c l u d e directive.
Headers TheC90standardheaderslist:
< a s s e r t . h > < c t y p e . h > < e r r n o . h > < f l o a t . h > < l i m i t s . h >
< l o c a l e . h > < m a t h . h > < s e t j m p . h > < s i g n a l . h > < s t d a r g . h >
HeadersaddedsinceC90:
#pragma
The pragma(pragmaticinformation)directiveispartofthestandard,[Link]#pragmadirectiveprovidesawaytorequestspecialbehaviorfromthe [Link]. Pragmasareusedwithinthesourceprogram.
# p r a g m at o k e n ( s )
NOTE:Othermethodsexisttodothisactionthatiscommonlyreferredasusing includeguards.
# d e f i n e
[Link]/wiki/C_Programming/Print_version
46/118
10/24/13
The # d e f i n e [Link],any errorsthatareintroducedby # d e f i n e aredifficulttotrace. Byconvention,valuesdefinedusing # d e f i n e [Link],[Link]. Today, # d e f i n e isprimarilyusedtohandlecompilerandplatformdifferences.E.g.,[Link] # d e f i n e shouldthusbelimitedunlessabsolutelynecessary t y p e d e f statements andconstantvariablescanoftenperformthesamefunctionsmoresafely. Anotherfeatureofthe # d e f i n e commandisthatitcantakearguments,[Link]:
# d e f i n eA B S O L U T E _ V A L U E (x)(( ( x )<0 )?( x ):( x )) . . . i n tx=1 ; w h i l e (A B S O L U T E _ V A L U E (x)){ . . . }
IfABSOLUTE_VALUE()werearealfunction'x'wouldnowhavethevalueof'9',butbecauseitwasanargumentinamacroitwasexpandedtwiceandthushasavalueof8.
Example: Toillustratethedangersofmacros,considerthisnaivemacro
# d e f i n eM A X ( a , b )a > b ? a : b
andthecode
i=M A X ( 2 , 3 ) + 5 ; j=M A X ( 3 , 2 ) + 5 ;
[Link]
i n ti=2 > 3 ? 2 : 3 + 5 ; i n tj=3 > 2 ? 3 : 2 + 5 ;
Thisworks,provided a , b [Link],
i=2 ; j=3 ; k=M A X ( i + + ,j + + ) ;
hasnoneofthepitfallsabove,butwillnotworkwithalltypes.
[Link]/wiki/C_Programming/Print_version
47/118
10/24/13
willmakethecompilerturnthiscommand
p u t s (a s _ s t r i n g (H e l l oW o r l d !));
into
p u t s (" H e l l oW o r l d ! ") ;
willmakethecompilerturn
p r i n t f (" % d " ,c o n c a t e n a t e (x ,y) ) ;
into
p r i n t f (" % d " ,x y ) ;
whichthemacroprocessorwillturninto
p u t s (" I ' me a t i n g"" f r u i t ""t o d a y . ")
whichinturnwillbeinterpretedbytheCparserasasinglestringconstant. Thefollowingtrickcanbeusedtoturnanumericconstantsintostringliterals
# d e f i n en u m 2 s t r ( x )s t r ( x )
[Link]/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 ) ) ;
[Link] anythingthathassideeffects,sincethiscanleadtobugs,thatappearanddisappeardependingonthecompilationparameters.
macros
Macrosaren'[Link],theydonotobeyscopeproperly,butsimplytakethestringpassedtothemandreplaceeachoccurrenceofthemacroargumentinthetextofthemacrowiththeactualstringfor thatparameter(thecodeisliterallycopiedintothelocationitwascalledfrom). Anexampleonhowtouseamacro:
# i n c l u d e< s t d i o . h > # d e f i n eS L I C E S8 # d e f i n eA D D ( x )(( x )/S L I C E S) i n tm a i n ( ) { i n ta=0 ,b=1 0 ,c=6 ; a=A D D ( b+c ) ; p r i n t f ( " % d \ n " ,a ) ; r e t u r n0 ; }
theresultof"a"shouldbe"2"(b+c=16>passedtoADD>16/SLICES>resultis"2")
#error
The #[Link].
# e r r o rm e s s a g e
#warning
Manycompilerssupporta #[Link],thecompileremitsadiagnosticcontainingtheremainingtokensinthedirective. 1. warningmessage
#undef
The #[Link].
#if,#else,#elif,#endif(conditionals)
[Link]/wiki/C_Programming/Print_version
49/118
10/24/13
The #ifcommandcheckswhetheracontrollingconditionalexpressionevaluatestozeroornonzero,[Link]:
# i f1 / *T h i sb l o c kw i l lb ei n c l u d e d* / # e n d i f # i f0 / *T h i sb l o c kw i l ln o tb ei n c l u d e d* / # e n d i f
#ifdef,#ifndef
The #ifdefcommandissimilarto # i f ,[Link],
# i f d e fN A M E
isequivalentto
# i fd e f i n e dN A M E
isequivalentto
# i f! d e f i n e dN A M E
UsefulPreprocessorMacrosforDebugging
ANSICdefinessomeusefulpreprocessormacrosandvariables, [7][8]alsocalled"magicconstants",include: __FILE__=>Thenameofthecurrentfile,asastringliteral __LINE__=>Currentlineofthesourcefile,asanumericliteral __DATE__=>Currentsystemdate,asastring __TIME__=>Currentsystemtime,asastring __TIMESTAMP__=>Dateandtime(nonstandard) __cplusplus=>undefinedwhenyourCcodeisbeingcompiledbyaCcompiler199711LwhenyourCcodeisbeingcompiledbyaC++compilercompliantwith1998C++standard. __func__=>Currentfunctionnameofthesourcefile,asastring(partofC99) __PRETTY_FUNCTION__=>"decorated"Currentfunctionnameofthesourcefile,asastring(inGCCnonstandard) Compiletimeassertions
[Link]/wiki/C_Programming/Print_version
50/118
10/24/13
Somepeople[9]defineapreprocessormacrotoallowcompiletimeassertions,somethinglike:
# d e f i n eC O M P I L E _ T I M E _ A S S E R T ( p r e d )s w i t c h ( 0 ) { c a s e0 : c a s ep r e d : ; } C O M P I L E _ T I M E _ A S S E R T (B O O L E A NC O N D I T I O N) ;
The s t a t i c _ a s s e r t . h p p [Link] 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][Link]".def"insteadofthetraditional".h".Thisfilecontainsalistofsimilarmacrocalls,which canbereferredtoas"componentmacros".[Link],theincludefileis"[Link]"anditcontainsalistofcomponentmacrosofthestyle"foo(x,y,z)".
# d e f i n ef o o ( x ,y ,z )d o S o m e t h i n g W i t h ( x ,y ,z ) ; # i n c l u d e" x m a c r o . d e f " # u n d e ff o o # d e f i n ef o o ( x ,y ,z )d o S o m e t h i n g E l s e W i t h ( x ,y ,z ) ; # i n c l u d e" x m a c r o . d e f " # u n d e ff o o ( e t c . . . )
File star_table.c:
t y p e d e fs t r u c t{ # d e f i n eE X P A N D _ E X P A N D _ S T A R _ M E M B E R ( m e m b e r ,t y p e )t y p em e m b e r ; # i n c l u d e" s t a r . d e f " }s t a r S t r u c t ; v o i ds e r i a l i z e _ s t a r ( c o n s ts t a r S t r u c t* c o n s ts t a r ,u n s i g n e dc h a r* b u f f e r ){ # d e f i n eE X P A N D _ E X P A N D _ S T A R _ M E M B E R ( m e m b e r ,t y p e )\ m e m c p y ( b u f f e r ,& ( s t a r > m e m b e r ) ,s i z e o f ( s t a r > m e m b e r ) ) ;\ b u f f e r+ =s i z e o f ( s t a r > m e m b e r ) ; # i n c l u d e" s t a r . d e f " } v o i dd e s e r i a l i z e _ s t a r ( s t a r S t r u c t* c o n s ts t a r ,c o n s tu n s i g n e dc h a r* b u f f e r ){ # d e f i n eE X P A N D _ E X P A N D _ S T A R _ M E M B E R ( m e m b e r ,t y p e )\ m e m c p y ( & ( s t a r > m e m b e r ) ,b u f f e r ,s i z e o f ( s t a r > m e m b e r ) ) ;\ b u f f e r+ =s i z e o f ( s t a r > m e m b e r ) ; # i n c l u d e" s t a r . d e f " }
[Link]/wiki/C_Programming/Print_version
51/118
10/24/13
# i n c l u d e" s t a r . d e f " }
Notethatinthisexampleyoucanalsoavoidthecreationofseparatehandlerfunctionsforeachdatatypeinthisexamplebydefiningtheprintformatforeachsupportedtype,withtheadditionalbenefitofreducingtheexpansioncodeproducedbythis headerfile:
# d e f i n eF O R M A T _ ( t y p e )F O R M A T _ # # t y p e # d e f i n eF O R M A T _ i n t " % d " # d e f i n eF O R M A T _ d o u b l e" % g " v o i dp r i n t _ s t a r ( c o n s ts t a r S t r u c t* c o n s ts t a r ){ / *F O R M A T _ ( t y p e )w i l lb er e p l a c e dw i t hF O R M A T _ i n to rF O R M A T _ d o u b l e* / # d e f i n eE X P A N D _ E X P A N D _ S T A R _ M E M B E R ( m e m b e r ,t y p e )\ p r i n t f ( " % s :"F O R M A T _ ( t y p e )" \ n " ,# m e m b e r ,s t a r > m e m b e r ) ; # i n c l u d e" s t a r . d e f " }
andtheprinthandlercouldbeaddedaswellas:
# d e f i n ep r i n t _ i n t ( v a l ) p r i n t f ( " % d " ,v a l ) # d e f i n ep r i n t _ d o u b l e ( v a l )p r i n t f ( " % g " ,v a l ) v o i dp r i n t _ s t a r ( c o n s ts t a r S t r u c t* c o n s ts t a r ){ / *p r i n t _ # # t y p ew i l lb er e p l a c e dw i t hp r i n t _ i n to rp r i n t _ d o u b l e* / # d e f i n eE X P A N D _ S T A R _ M E M B E R ( m e m b e r ,t y p e )\ p r i n t f ( " % s :" ,# m e m b e r ) ;\ p r i n t _ # # t y p e ( s t a r > m e m b e r ) ;\ p r i n t f ( " \ n " ) ; E X P A N D _ S T A R # u n d e fE X P A N D _ S T A R _ M E M B E R }
oras:
# d e f i n eF O R M A T _ ( t y p e )F O R M A T _ # # t y p e # d e f i n eF O R M A T _ i n t " % d " # d e f i n eF O R M A T _ d o u b l e" % g " v o i dp r i n t _ s t a r ( c o n s ts t a r S t r u c t* c o n s ts t a r ){ / *F O R M A T _ ( t y p e )w i l lb er e p l a c e dw i t hF O R M A T _ i n to rF O R M A T _ d o u b l e* / # d e f i n eE X P A N D _ S T A R _ M E M B E R ( m e m b e r ,t y p e )\ p r i n t f ( " % s :"F O R M A T _ ( t y p e )" \ n " ,# m e m b e r ,s t a r > m e m b e r ) ; E X P A N D _ S T A R # u n d e fE X P A N D _ S T A R _ M E M B E R
[Link]/wiki/C_Programming/Print_version
52/118
10/24/13
}
Thisapproachcanbedangerousinthattheentiremacrosetisalwaysinterpretedasifitwasonasinglesourceline,whichcouldencountercompilerlimitswithcomplexcomponentmacrosand/orlongmemberlists. ThistechniquewasreportedbyLarsWirzenius[15]inawebpagedatedJanuary17,2000,inwhichhegivescredittoKennethOksanenfor"refininganddeveloping"[Link] decadebeforetheturnofthecentury. 1. Severalprogrammersrecommend"[Link]."[1]([Link] ([Link] tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5]([Link] 3. [[Link] 4. "CodingConventionsforC++andJava"([Link] Thisdeliberatechoicewasmadebecausealigningthoseprettystarsisalargewasteoftimeanddiscouragesthemaintenanceofinlinecomments.", 5. wiki:BigBlocksOfAsterisks,"Codecraft"([Link] 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"([Link]
Libraries
A libraryinCisagroupoffunctionsanddeclarations,[Link] interfaceexpressedina . h file(namedthe"header")andan implementationexpressedina . c [Link] . c filemightbe precompiledorotherwiseinaccessible,oritmightbeavailabletotheprogrammer.(Note:LibrariesmaycallfunctionsinotherlibrariessuchastheStandardCormathlibrariestodovarioustasks.) [Link],intheUnixandLinuxoperatingsystems,alibraryconsistsofoneormore objectfiles,whichconsistofobjectcodethatisusuallytheoutputofacompiler(if thesourcelanguageisCorsomethingsimilar)oranassembler(ifthesourcelanguageisassemblylanguage).Theseobjectfilesarethenturnedintoalibraryintheformofanarchivebythe ararchiver(aprogramthattakesfilesandstoresthemina biggerfilewithoutregardtocompression).Thefilenameforthelibraryusuallystartswith"lib"andendswith".a"[Link] [Link]"libm.a"themathematicsroutines,[Link]
[Link]/wiki/C_Programming/Print_version
53/118
10/24/13
operatingsystemssuchasMicrosoftWindowsusea".lib"extensionforlibrariesandan".obj"extensionforobjectfiles. We'[Link]:
i
haveanoptionalargumentthatisconcatenated([Link]
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 ;
[Link]/wiki/C_Programming/Print_version
54/118
10/24/13
r e t u r n' ? ' ; } e l s e / *f l a gv a l u ei sn e x tt o k e n* / o p t a r g=a r g v [ o p t i n d + + ] ; s p=1 ; } e l s e { / *s e tu pt ol o o ka tn e x tc h a ri nt o k e n ,n e x tt i m e* / i f( a r g v [ o p t i n d ] [ + + s p ]= =' \ 0 ' ) { / *n om o r ei nc u r r e n tt o k e n ,s os e t u pn e x tt o k e n* / s p=1 ; o p t i n d + + ; } o p t a r g=0 ; } r e t u r no p t o p t ; } / *E N DO FF I L E* /
Theinterfacewouldbethefollowing"getopt.h"file:
# i f n d e fG E T O P T _ H # d e f i n eG E T O P T _ H / *e x p o r t e dv a r i a b l e s* / e x t e r ni n to p t e r r ,o p t i n d ,o p t o p t ; e x t e r nc h a r* o p t a r g ; / *e x p o r t e df u n c t i o n* / i n tg e t o p t ( i n t ,c h a r* * ,c h a r* ) ; # e n d i f / *E N DO FF I L E* /
Ataminimum,aprogrammerhastheinterfacefiletofigureouthowtousealibrary,although,ingeneral,[Link],thedocumentationshouldsaythattheprovided arguments * * a r g v and * o p t s bothshouldn'tbenullpointers(orwhywouldyoubeusingthe g e t o p t functionanyway?).Specifically,[Link] usealibrary,arenormallynotinterestedintheimplementationofthelibraryunlesstheimplementationhasabug,inwhichcasehewouldwanttocomplainsomehow. Boththeimplementationofthegetoptslibrary,andprogramsthatusethelibraryshouldstate # i n c l u d e" g e t o p t . h " ,[Link]"linked"totheprogramtheonethatcontainsthemain()[Link] programmayrefertodozensofinterfaces. Insomecases,justplacing # i n c l u d e" g e t o p t . h " [Link],[Link]'s documentationorlibrary'sdocumentationonhowtoresolvethisissue.
Whattoputinheaderfiles
Asageneralrule,headerscontainanythingthatshouldbeexported,or"seen"[Link](preprocessor # d e f i n e s)structure,union,andenumerationdeclarationstypedefdeclarationsexternal [Link] 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 [Link] g e t o p t . h filewereincludedmorethanonceinatranslationunit,theunitwouldonlyseethecontentsonce.
Furtherreading
CFAQ:"I'[Link].(Whatdoes".h"mean,anyway?)"([Link] PIClistthread:"GlobalvariablesinprojectswithmanyCfiles."([Link]
Standardlibraries
The Cstandardlibraryisastandardizedcollectionofheaderfilesandlibraryroutinesusedtoimplementcommonoperations,suchasinput/[Link](suchasCOBOL,Fortran,andPL/I)Cdoesnot includebuiltinkeywordsforthesetasks,sonearlyallCprogramsrelyonthestandardlibrarytofunction.
History
TheCprogramminglanguagepreviouslydidnotprovideanyelementaryfunctionalities,suchasI/[Link],[Link],andwere [Link] Cstandardlibraries. BothUnixandCwerecreatedatAT&T'sBellLaboratoriesinthelate1960sandearly1970s.Duringthe1970stheCprogramminglanguagebecameincreasinglypopular,withmanyuniversitiesandorganizationsbeginningtocreatetheirownvariationsof thelanguagefortheirownprojects.Bythestartofthe1980scompatibilityproblemsbetweenthevariousCimplementationsbecameapparent.In1983theAmericanNationalStandardsInstitute(ANSI)formedacommitteetoestablishastandard specificationofCknownas"ANSIC".Thisworkculminatedinthecreationofthesocalled [Link] ANSICstandardlibrary. [Link].
[Link]/wiki/C_Programming/Print_version
55/118
10/24/13
Theheaders <iso646.h>, <wchar.h>,and <wctype.h>wereaddedwithNormativeAddendum1(hereafterabbreviatedas NA1),anadditiontotheCStandardratifiedin1995. Theheaders <complex.h>, <fenv.h>, <inttypes.h>, <stdbool.h>, <stdint.h>,and <tgmath.h>wereaddedwith C99,arevisiontotheCStandardpublishedin1999.
Design
Thedeclarationofeachfunctioniskeptinaheaderfile,[Link] [Link],astandardlibrarywithaparticularcompilerismostlyincompatiblewithstandardlibrariesofothercompilers. [Link],withthebenefitofhindsight,[Link] g e t s ( ) (andtheuseof s c a n f ( ) toreadstringinput)arethesourceofmanybuffer overflows,[Link] s t r t o k ( ) ,afunctionthatisdesignedasaprimitivelexicalanalyserbutishighly"fragile"anddifficulttouse.
ANSIStandard
TheANSICstandardlibraryconsistsof24Cheaderfileswhichcanbeincludedintoaprogrammer'[Link],[Link] headerfilesfollows. Incomparisontosomeotherlanguages(forexampleJava)[Link],stringmanipulation,typeconversions,andfileandconsolebasedI/[Link] setof"containertypes"liketheC++StandardTemplateLibrary,letalonethecompletegraphicaluserinterface(GUI)toolkits,networkingtools,[Link] libraryisthatprovidingaworkingANSICenvironmentismucheasierthanitiswithotherlanguages,andconsequentlyportingCtoanewplatformisrelativelyeasy. [Link],theGNOMEdesktopenvironmentprojecthasdevelopedtheGTK+graphicstoolkitandGLib,alibrary ofcontainerdatastructures,[Link] 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()[Link]. 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. [Link] 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)
[Link]/wiki/C_Programming/Print_version
56/118
10/24/13
Commonsupportlibraries
Whilenotstandardized,[Link],forexample,beforecalling m a i n ( ) ,isimplementedintheC RunTimeLibraryforagivenvendor'[Link],likehandlinguncaughtexceptionsorimplementingfloatingpointcode. TheCstandardlibraryonlydocumentsthatthespecificroutinesmentionedinthisarticleareavailable,[Link],itis likelythevendorspecificroutinesarepackagedwiththeCStandardLibraryinthesamemodule,becausethey'rebothlikelytobeneededbyanyprogrambuiltwiththeirtoolset. ThoughoftenconfusedwiththeCStandardLibrarybecauseofthispackaging,theCRuntimeLibraryisnotastandardizedpartofthelanguageandisvendorspecific.
Compilerbuiltinfunctions
Somecompilers(forexample,GCC)providebuiltinversionsofmanyofthefunctionsintheCstandardlibrarythatis,theimplementationsofthefunctionsarewrittenintothecompiledobjectfile,andtheprogramcallsthebuiltinversionsinsteadofthe [Link],especiallyiffunctioncallsarereplacedwithinlinevariants,andallowsotherformsofoptimization(asthecompilerknowsthecontrolflowcharacteristicsofthebuiltin variants),butmaycauseconfusionwhendebugging(forexample,thebuiltinversionscannotbereplacedwithinstrumentedvariants).
POSIXstandardlibrary
POSIX,(alongwiththeSingleUnixSpecification),specifiesanumberofroutinesthatshouldbeavailableoverandabovethoseintheCstandardlibrarypropertheseareoftenimplementedalongsidetheCstandardlibraryfunctionality,withvarying [Link],[Link],[Link],thisPOSIXspecifiedfunctionalitywillberegardedaspartof thelibrarytheClibrarypropermaybeidentifiedastheANSIorISOClibrary.
FileIO
Introduction
The s t d i o . h [Link] alsorequiresmoreexplanationbecauseofthecomplexmachinerythatunderliesthefunctions. Thedeviceindependentmodelofinputandoutputhasseendramaticimprovementovertheyearsandhasreceivedlittlerecognitionforitssuccess.FORTRANIIwastoutedasamachineindependentlanguageinthe1960s,yetitwasessentially [Link],[Link],yousaid R E A DI N P U TT A P E5 ona tapeorientedIBM7090but R E A DC A R D [Link] R E A D and W R I T E statements,specifyinga logicalunitnumber(LUN)[Link]/Ohaddawned. [Link], [Link],eachmanufacturerof consolessolvedproblemssuchasconsolecursormovementinanindependentmanner,causingfurtherheadaches. [Link],thedevelopersofUnix,[Link]. TheANSIC < s t d i o . h > libraryisbasedontheoriginalUnixfileI/Oprimitivesbutcastsawidernettoaccommodatetheleastcommondenominatoracrossvariedsystems.
Streams
Inputandoutput,whethertoorfromphysicaldevicessuchasterminalsandtapedrives,orwhethertoorfromfilessupportedonstructuredstoragedevices,aremappedintologicaldatastreams,whosepropertiesaremoreuniformthantheirvarious [Link]:textstreamsandbinarystreams. [Link].(Theonlyexceptionisthatinsomeimplementationsthelastlineofafiledoesnotrequireaterminatingnewline character.)[Link]'swhatanyprogramexpectswhenitreadstext,andthat'swhatanyprogramproduceswhenitwritestext.(Thisisthe mostbasicconvention,andifitdoesn'tmeettheneedsofatextorientedperipheralattachedtoaUnixmachine,[Link].)Thestringofcharactersthatgointo,orcome [Link],insomeimplementationswhenaspacecharacter precedesanewlinecharacterintheinput,[Link],whenthedataonlyconsistsofprintablecharactersandcontrolcharacterslikehorizontaltabandnewline,theinputandoutputofatextstreamare equal. Comparedtoatextstream,[Link] [Link],however,[Link]. NothinginUnixpreventstheprogramfromwritingarbitrary8bitbinarycodestoanyopenfile,[Link],Unixobliteratedthelongstandingdistinctionbetweentextstreamsandbinarystreams.
StandardStreams
WhenaCprogramstartsitsexecutiontheprogramautomaticallyopensthreestandardstreamsnamed s t d i n , s t d o u t ,and s t d e r r .TheseareattachedforeveryCprogram. [Link]. 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 .* /
[Link]/wiki/C_Programming/Print_version
57/118
10/24/13
r e t u r n0 ; } / *e n dp r o g r a m .* /
F I L E pointers
The < s t d i o . h > headercontainsadefinitionforatype F I L E (usuallyviaa t y p e d e f )whichiscapableofprocessingalltheinformationneededtoexercisecontroloverastream,includingitsfilepositionindicator,apointertotheassociatedbuffer(ifany),anerror indicatorthatrecordswhetheraread/writeerrorhasoccurred,andanendoffileindicatorthatrecordswhethertheendofthefilehasbeenreached. Itisconsideredbadmannerstoaccessthecontentsof F I L E directlyunlesstheprogrammeriswritinganimplementationof < s t d i o . h > [Link] 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 [Link],[Link]
r w a r b w b a b r + w + a + r + bo rr b + w + bo rw b + a + bo ra b +
Openingafilewithreadmode('r 'asthefirstcharacterinthe m o d e argument)failsifthefiledoesnotexistorcannotberead. Openingafilewithappendmode('a 'asthefirstcharacterinthe m o d e argument)causesallsubsequentwritestothefiletobeforcedtothethencurrentendoffile,regardlessofinterveningcallstothe f s e e k [Link],openinga binaryfilewithappendmode('b 'asthesecondorthirdcharacterintheabovelistof m o d e arguments)mayinitiallypositionthefilepositionindicatorforthestreambeyondthelastdatawritten,becauseofnullcharacterpadding. Whenafileisopenedwithupdatemode('+ 'asthesecondorthirdcharacterintheabovelistof m o d e argumentvalues),[Link],outputmaynotbedirectlyfollowedbyinputwithoutan interveningcalltothe f f l u s h functionortoafilepositioningfunction(f s e e k , f s e t p o s ,or r e w i n d ),andinputmaynotbedirectlyfollowedbyoutputwithoutaninterveningcalltoafilepositioningfunction,unlesstheinputoperationencountersendoffile. Opening(orcreating)atextfilewithupdatemodemayinsteadopen(orcreate)abinarystreaminsomeimplementations. Whenopened,astreamisfullybufferedifandonlyifitcanbedeterminednottorefertoaninteractivedevice.
ClosingFiles
# i n c l u d e< s t d i o . h > i n tf c l o s e ( F I L E* s t r e a m ) ;
Otherfileaccessfunctions
Thef f l u s h function
# i n c l u d e< s t d i o . h > i n tf f l u s h ( F I L E* s t r e a m ) ;
[Link]/wiki/C_Programming/Print_version
58/118
10/24/13
If s t r e a m pointstoanoutputstreamoranupdatestreaminwhichthemostrecentoperationwasnotinput,the f f l u s h [Link] 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 [Link],thewritefunctionswillcall f f l u s h to actually"write"[Link] f f l u s h isonlycalledeveryonceinawhile,callstotheoperatingsystemtodoarawwriteareminimized.
Thes e t b u f function
# i n c l u d e< s t d i o . h > v o i ds e t b u f ( F I L E* s t r e a m ,c h a r* b u f ) ;
Thes e t v b u f function
# i n c l u d e< s t d i o . h > i n ts e t v b u f ( F I L E* s t r e a m ,c h a r* b u f ,i n tm o d e ,s i z e _ ts i z e ) ;
The s e t v b u f functionmaybeusedonlyafterthestreampointedtoby s t r e a m [Link] 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/[Link] b u f isnotanullpointer,thearrayitpointstomaybeusedinsteadofabufferassociatedbythe s e t v b u f function.(The buffermusthavealifetimeatleastasgreatastheopenstream,sothestreamshouldbeclosedbeforeabufferthathasautomaticstoragedurationisdeallocateduponblockexit.)Theargument s i z e [Link] arrayatanytimeareindeterminate. The s e t v b u f functionreturnszeroonsuccess,ornonzeroifaninvalidvalueisgivenfor m o d e oriftherequestcannotbehonored.
FunctionsthatModifytheFilePositionIndicator
The s t d i o . h libraryhasfivefunctionsthataffectthefilepositionindicatorbesidesthosethatdoreadingorwriting: f g e t p o s , f s e e k , f s e t p o s , f t e l l ,and r e w i n d . The f s e e k and f t e l l functionsareolderthan f g e t p o s and f s e t p o s .
The f g e t p o s functionstoresthecurrentvalueofthefilepositionindicatorforthestreampointedtoby s t r e a m intheobjectpointedtoby p o s .Thevaluestoredcontainsunspecifiedinformationusablebythe f s e t p o s functionforrepositioningthestreamtoits positionatthetimeofthecalltothe f g e t p o s function. Ifsuccessful,the f g e t p o s functionreturnszeroonfailure,the f g e t p o s functionreturnsnonzeroandstoresanimplementationdefinedpositivevaluein e r r n o . The f s e t p o s functionsetsthefilepositionindicatorforthestreampointedtoby s t r e a m accordingtothevalueoftheobjectpointedtoby p o s ,whichshallbeavalueobtainedfromanearliercalltothe f g e t p o s functiononthesamestream. Asuccessfulcalltothe f s e t p o s functionclearstheendoffileindicatorforthestreamandundoesanyeffectsofthe u n g e t c [Link] f s e t p o s call,thenextoperationonanupdatestreammaybeeitherinputoroutput. Ifsuccessful,the f s e t p o s functionreturnszeroonfailure,the f s e t p o s functionreturnsnonzeroandstoresanimplementationdefinedpositivevaluein e r r n o .
The f s e e k functionsetsthefilepositionindicatorforthestreampointedtoby s t r e a m . Forabinarystream,thenewposition,measuredincharactersfromthebeginningofthefile,isobtainedbyadding o f f s e t tothepositionspecifiedby w h e n c e .Threemacrosin s t d i o . h called S E E K _ S E T , S E E K _ C U R ,and S E E K _ E N D [Link] 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 ,[Link] 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.
[Link]/wiki/C_Programming/Print_version
59/118
10/24/13
The f t e l l functionobtainsthecurrentvalueofthefilepositionindicatorforthestreampointedtoby s t r e a m .Forabinarystream,thevalueisthenumberofcharactersfromthebeginningofthefileforatextstream,itsfilepositionindicatorcontains unspecifiedinformation,usablebythe f s e e k functionforreturningthefilepositionindicatorforthestreamtoitspositionatthetimeofthe f t e l l callthedifferencebetweentwosuchreturnvaluesisnotnecessarilyameaningfulmeasureofthenumberof characterswrittenorread. Ifsuccessful,the f t e l l [Link],the f t e l l functionreturns 1 L andstoresanimplementationdefinedpositivevaluein e r r n o .
Ther e w i n d function
# i n c l u d e< s t d i o . h > v o i dr e w i n d ( F I L E* s t r e a m ) ;
exceptthattheerrorindicatorforthestreamisalsocleared.
ErrorHandlingFunctions
Thec l e a r e r r function
# i n c l u d e< s t d i o . h > v o i dc l e a r e r r ( F I L E* s t r e a m ) ;
The c l e a r e r r functionclearstheendoffileanderrorindicatorsforthestreampointedtoby s t r e a m .
Thef e o f function
# i n c l u d e< s t d i o . h > i n tf e o f ( F I L E* s t r e a m ) ;
Thef e r r o r function
# i n c l u d e< s t d i o . h > i n tf e r r o r ( F I L E* s t r e a m ) ;
Thep e r r o r function
# i n c l u d e< s t d i o . h > v o i dp e r r o r ( c o n s tc h a r* s ) ;
The p e r r o r functionmapstheerrornumberintheintegerexpression e r r n o [Link]:first,if s isnotanullpointerandthecharacterpointedtoby s isnotthenullcharacter,the stringpointedtoby s followedbyacolon(: )[Link] 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 ) ;
[Link]/wiki/C_Programming/Print_version
60/118
10/24/13
Ther e n a m e function
# i n c l u d e< s t d i o . h > i n tr e n a m e ( c o n s tc h a r* o l d _ f i l e n a m e ,c o n s tc h a r* n e w _ f i l e n a m e ) ;
The r e n a m e functioncausesthefilewhosenameisthestringpointedtoby o l d _ f i l e n a m e tobehenceforthknownbythenamegivenbythestringpointedtoby n e w _ f i l e n a m e .Thefilenamed o l d _ f i l e n a m e [Link] stringpointedtoby n e w _ f i l e n a m e existspriortothecalltothe r e n a m e function,thebehaviorisimplementationdefined. The r e n a m e functionreturnszeroiftheoperationsucceeds,nonzeroifitfails,inwhichcaseifthefileexistedpreviouslyitisstillknownbyitsoriginalname.
Thet m p f i l e function
# i n c l u d e< s t d i o . h > F I L E* t m p f i l e ( v o i d ) ;
Thet m p n a m function
# i n c l u d e< s t d i o . h > c h a r* t m p n a m ( c h a r* s ) ;
The t m p n a m functiongeneratesastringthatisavalidfilenameandthatisnotthenameofanexistingfile. The t m p n a m functiongeneratesadifferentstringeachtimeitiscalled,upto T M P _ M A X times.(T M P _ M A X isamacrodefinedin s t d i o . h .)Ifitiscalledmorethan T M P _ M A X times,thebehaviorisimplementationdefined. Theimplementationshallbehaveasifnolibraryfunctioncallsthe t m p n a m function. Iftheargumentisanullpointer,the t m p n a m [Link] t m p n a m [Link],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 [Link],[Link],thearraycontents areindeterminateandanullpointerisreturned. Warning:[Link],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.
[Link]/wiki/C_Programming/Print_version
61/118
10/24/13
/ *Ae x a m p l ep r o g r a mt h a tr e a d sf r o ms t d i na n dw r i t e st os t d o u t* / # i n c l u d e< s t d i o . h > # d e f i n eB U F F E R _ S I Z E1 0 0 i n tm a i n ( v o i d ) { c h a rb u f f e r [ B U F F E R _ S I Z E ] ;/ *ar e a db u f f e r* / w h i l e (f g e t s( b u f f e r ,B U F F E R _ S I Z E ,s t d i n )! =N U L L ) { p r i n t f ( " % s " , b u f f e r ) ; } r e t u r n0 ; } / *e n dp r o g r a m .* /
The g e t c function
# i n c l u d e< s t d i o . h > i n tg e t c ( F I L E* s t r e a m ) ;
The g e t c functionisequivalentto f g e t c ,[Link],the s t r e a m argumentmaybeevaluatedmorethanonce,sotheargumentshouldneverbeanexpressionwithsideeffects([Link] 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 [Link],andanullcharacteriswrittenimmediately afterthelastcharacterreadintothearray. The g e t s functionreturns s [Link],[Link],thearray contentsareindeterminateandanullpointerisreturned. [Link] g e t s ,[Link]#5of HenrySpencer's TheTenCommandmentsforCProgrammers(AnnotatedEdition)reads,"Thoushaltcheckthearrayboundsofallstrings(indeed,allarrays),forsurelywherethoutypest foosomeonesomedayshalltype supercalifragilisticexpialidocious." Itmentions g e t s intheannotation:"AsdemonstratedbythedeedsoftheGreatWorm,aconsequenceofthiscommandmentisthatrobustproductionsoftwareshouldnevermakeuseof g e t s ( ) ,[Link] 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 )[Link].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 )[Link]. [Link] u n g e t c functioniscalledtoomanytimesonthesamestreamwithoutaninterveningreadorfilepositioningoperationonthatstream,theoperationmayfail. Ifthevalueof c equalsthatofthemacro E O F ,theoperationfailsandtheinputstreamisunchanged.
[Link]/wiki/C_Programming/Print_version
Asuccessfulcalltothe u n g e t c [Link]
62/118
10/24/13
EOFpitfall
Amistakewhenusing f g e t c , g e t c ,or g e t c h a r istoassigntheresulttoavariableoftype c h a r beforecomparingitto E O F .Thefollowingcodefragmentsexhibitthismistake,andthenshowthecorrectapproach(usingtypeint): Mistake
c h a rc ; w h i l e( ( c=g e t c h a r ( ) )! =E O F ) p u t c h a r ( c ) ; i n tc ; w h i l e( ( c=g e t c h a r ( ) )! =E O F ) p u t c h a r ( c ) ;
Correction
Considerasysteminwhichthetype c h a r is8bitswide,representing256differentvalues. g e t c h a r mayreturnanyofthe256possiblecharacters,anditalsomayreturn E O F toindicateendoffile,foratotalof257differentpossiblereturnvalues. When g e t c h a r 'sresultisassignedtoa c h a r ,whichcanrepresentonly256differentvalues,thereisnecessarilysomelossofinformationwhenpacking257itemsinto256slots,[Link] E O F value,whenconvertedto c h a r ,becomes [Link],theaboveexamplemaymistakeitforanendoffileindicatoror,justasbad,iftype c h a r isunsigned,thenbecause E O F isnegative, itcanneverbeequaltoanyunsigned c h a r ,[Link],repeatedlyprintingthecharacterwhichresultsfromconverting E O F to c h a r . However,thisloopingfailuremodedoesnotoccurifthechardefinitionissigned(Cmakesthesignednessofthedefaultchartypeimplementationdependent), [16]assumingthecommonlyused E O F [Link],thefundamentalissueremainsthat ifthe E O F valueisdefinedoutsideoftherangeofthe c h a r type,whenassignedtoa c h a r thatvalueisslicedandwillnolongermatchthefull E O F [Link],if E O F iswithinrangeof c h a r ,thisguaranteesacollision between E O F [Link],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'[Link] 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 [Link] extrachecksarerarelydone,becausemostprogrammersassumethattheircodewillneverneedtorunononeofthese"big c h a r "[Link] 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 [Link],[Link],itsvalueisindeterminate. The f r e a d functionreturnsthenumberofelementssuccessfullyread,whichmaybelessthan n m e m b [Link] 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 [Link],[Link],theexcessargumentsareevaluated(asalways)butareotherwiseignored. Theformatshallbeamultibytecharactersequence,[Link]:oneormorewhitespacecharactersanordinarymultibytecharacter(neither % orawhitespace character)[Link] % .Afterthe % ,thefollowingappearinsequence: Anoptionalassignmentsuppressingcharacter * . Anoptionalnonzerodecimalintegerthatspecifiesthemaximumfieldwidth. Anoptional h , l (ell)or L [Link] 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. [Link].
[Link]/wiki/C_Programming/Print_version
63/118
10/24/13
The f s c a n f [Link],asdetailedbelow,the f s c a n f [Link](duetotheunavailabilityofinputcharacters)ormatchingfailures(duetoinappropriate input). Adirectivecomposedofwhitespacecharacter(s)isexecutedbyreadinginputuptothefirstnonwhitespacecharacter(whichremainsunread)oruntilnomorecharactersremainunread. [Link],thedirectivefails,andthedifferingandsubsequentcharactersremainunread. Adirectivethatisaconversionspecificationdefinesasetofmatchinginputsequences,[Link]: Inputwhitespacecharacters(asspecifiedbythe i s s p a c e function)areskipped,unlessthespecificationincludesa [ , c ,or n specifier.(Thewhitespacecharactersarenotcountedagainstthespecifiedfieldwidth.) Aninputitemisreadfromthestream,unlessthespecificationincludesan n [Link],unlessthatexceedsaspecifiedfieldwidth,inwhichcaseitistheinitialsubsequenceof [Link],ifany,[Link],theexecutionofthedirectivefailsthisconditionisamatchingfailure,unlessanerrorpreventedinputfromthestream,in whichcaseitisaninputfailure. Exceptinthecaseofa % specifier,theinputitem(or,inthecaseofa % n directive,thecountofinputcharacters)[Link],theexecutionofthedirectivefails [Link] * ,theresultoftheconversionisplacedintheobjectpointedtobythefirstargumentfollowingthe f o r m a t [Link] thisobjectdoesnothaveanappropriatetype,oriftheresultoftheconversioncannotberepresentedinthespaceprovided,thebehaviorisundefined. Thefollowingconversionspecifiersarevalid:
d
Matchesanoptionallysignedfloatingpointnumber,whoseformatisthesameasexpectedforthesubjectstringofthe s t r t o d [Link].
s
Matchesasequenceofnonwhitespacecharacters.(Nospecialprovisionsaremadeformultibytecharacters.)Thecorrespondingargumentshallbeapointertotheinitialcharacterofanarraylargeenoughtoacceptthesequenceandaterminating nullcharacter,whichwillbeaddedautomatically.
[
Matchesanonemptysequenceofcharacters(nospecialprovisionsaremadeformultibytecharacters)fromasetofexpectedcharacters(the scanset ).Thecorrespondingargumentshallbeapointertotheinitialcharacterofanarraylargeenough toacceptthesequenceandaterminatingnullcharacter,[Link] f o r m a t string,uptoandincludingthematchingrightbracket(] ).Thecharactersbetween thebrackets(the scanlist )comprisethescanset,unlessthecharacteraftertheleftbracketisacircumflex(^ ),[Link] conversionspecifierbeginswith [ ] or [ ^ ] ,therightbracketcharacterisinthescanlistandthenextrightbracketcharacteristhematchingrightbracketthatendsthespecificationotherwise,thefirstrightbracketcharacteristheonethatendsthe [Link] characterisinthescanlistandisnotthefirst,northesecondwherethefirstcharacterisa ^ ,northelastcharacter,thebehaviorisimplementationdefined.
c
Matchesasequenceofcharacters(nospecialprovisionsaremadeformultibytecharacters)ofthenumberspecifiedbythefieldwidth(1ifnofieldwidthispresentinthedirective).Thecorrespondingargumentshallbeapointertotheinitial [Link].
p
Matchesasingle % [Link] % % .
[Link]/wiki/C_Programming/Print_version
64/118
10/24/13
Ifaconversionspecificationisinvalid,thebehaviorisundefined.
Theconversionspecifiers E , G ,and X arealsovalidandbehavethesameas,respectively, e , g ,and x . Ifendoffileisencounteredduringinput,[Link](otherthanleadingwhitespace,wherepermitted),executionofthecurrentdirectiveterminates withaninputfailureotherwise,unlessexecutionofthecurrentdirectiveisterminatedwithamatchingfailure,executionofthefollowingdirective(ifany)isterminatedwithaninputfailure. Ifconversionterminatesonaconflictinginputcharacter,[Link](includingnewlinecharacters)[Link] suppressedassignmentsisnotdirectlydeterminableotherthanviathe % n directive. The f s c a n f functionreturnsthevalueofthemacro E O F [Link],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,[Link] f s c a n f [Link] copyingtakesplacebetweenobjectsthatoverlap,thebehaviorisundefined.
WritingtoFiles
CharacterOutputFunctions
The f p u t c function
# i n c l u d e< s t d i o . h > i n tf p u t c ( i n tc ,F I L E* s t r e a m ) ;
# i n c l u d e< s t d i o . h > i n tf p u t s ( c o n s tc h a r* s ,F I L E* s t r e a m ) ;
# i n c l u d e< s t d i o . h > i n tp u t c ( i n tc ,F I L E* s t r e a m ) ;
# i n c l u d e< s t d i o . h > i n tp u t c h a r ( i n tc ) ;
# i n c l u d e< s t d i o . h > i n tp u t s ( c o n s tc h a r* s ) ;
Directoutputfunction:thef w r i t e function
[Link]/wiki/C_Programming/Print_version
65/118
10/24/13
# i n c l u d e< s t d i o . h > s i z e _ tf w r i t e ( c o n s tv o i d* p t r ,s i z e _ ts i z e ,s i z e _ tn m e m b ,F I L E* s t r e a m ) ;
Formattedoutputfunctions:thep r i n t f familyoffunctions
# i n c l u d e< s t d a r g . h > # i n c l u d e< s t d i o . h > i n tf p r i n t f ( F I L E* s t r e a m ,c o n s tc h a r* f o r m a t ,. . . ) ; i n tp r i n t f ( c o n s tc h a r* f o r m a t ,. . . ) ; i n ts p r i n t f ( c h a r* s ,c o n s tc h a r* f o r m a t ,. . . ) ; i n tv f p r i n t f ( F I L E* s t r e a m ,c o n s tc h a r* f o r m a t ,v a _ l i s ta r g ) ; i n tv p r i n t f ( c o n s tc h a r* f o r m a t ,v a _ l i s ta r g ) ; i n tv s p r i n t f ( c h a r* s ,c o n s tc h a r* f o r m a t ,v a _ l i s ta r g ) ;
Note:[Link],whichadheretotheC89/[Link],thenewoneswillbemarkedwith(C99). The f p r i n t f functionwritesoutputtothestreampointedtoby s t r e a m undercontrolofthestringpointedtoby f o r m a t [Link],thebehavioris [Link],theexcessargumentsareevaluated(asalways)[Link] f p r i n t f functionreturnswhentheendoftheformatstringisencountered. Theformatshallbeamultibytecharactersequence,[Link]:ordinarymultibytecharacters(not % ),whicharecopiedunchangedtotheoutputstreamandconversion specifications,eachofwhichresultsinfetchingzeroormoresubsequentarguments,convertingthem,ifapplicable,accordingtothecorrespondingconversionspecifier,andthenwritingtheresulttotheoutputstream. Eachconversionspecificationisintroducedbythecharacter % .Afterthe % ,thefollowingappearinsequence: Zeroormoreflags(inanyorder)thatmodifythemeaningoftheconversionspecification. [Link],itispaddedwithspaces(bydefault)ontheleft(orright,iftheleftadjustmentflag,describedlater,hasbeengiven)[Link] 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 [Link](. )followedeitherbyanasterisk * (describedlater)orbyanoptionaldecimalintegerif onlytheperiodisspecified,[Link],[Link] roundedtofittheprecisioni.e. p r i n t f ( " % 1 . 1 f \ n " ,1 . 1 9 ) ; produces 1 . 2 . Anoptionallengthmodifierthatspecifiesthesizeoftheargument. Aconversionspecifiercharacterthatspecifiesthetypeofconversiontobeapplied. Asnotedabove,afieldwidth,orprecision,orboth,[Link],an i n t [Link],orprecision,orboth,shallappear(inthatorder)beforethe argument(ifany)[Link] [Link]. Theflagcharactersandtheirmeaningsare:
Theresultoftheconversionisleftjustifiedwithinthefield.(Itisrightjustifiedifthisflagisnotspecified.)
+
Theresultisconvertedtoan"alternativeform".For o conversion,itincreasestheprecision,ifandonlyifnecessary,toforcethefirstdigitoftheresulttobeazero(ifthevalueandprecisionareboth0,asingle0isprinted).For x (or X )conversion,a nonzeroresulthas 0 x (or 0 X )[Link] a , A , e , E , f , F , g ,and G conversions,theresultalwayscontainsadecimalpointcharacter,evenifnodigitsfollowit.(Normally,adecimalpointcharacterappearsintheresultoftheseconversionsonlyifa digitfollowsit.)For g and G conversions,[Link],thebehaviorisundefined.
0
Thelengthmodifiersandtheirmeaningsare:
h h
[Link]/wiki/C_Programming/Print_version
66/118
10/24/13
Specifiesthatafollowing d , i , o , u , x ,or X conversionspecifierappliestoa l o n gi n t or u n s i g n e dl o n gi n t argumentthatafollowing n conversionspecifierappliestoapointertoa l o n gi n t argument(C99)thatafollowing c conversionspecifierappliesto a w i n t _ t argument(C99)thatafollowing s conversionspecifierappliestoapointertoa w c h a r _ t argumentorhasnoeffectonafollowing a , A , e , E , f , F , g ,or G conversionspecifier.
l l (ellell)
The u n s i g n e di n t argumentisconvertedtounsignedoctal(o ),unsigneddecimal(u ),orunsignedhexadecimalnotation(x or X )inthestyle ddddtheletters a b c d e f areusedfor x conversionandtheletters A B C D E F for X [Link] theminimumnumberofdigitstoappearifthevaluebeingconvertedcanberepresentedinfewerdigits,[Link].
f , F
A d o u b l e argumentrepresentinga(finite)floatingpointnumberisconvertedtodecimalnotationinthestyle [ ]ddd. ddd,[Link],it istakenas6iftheprecisioniszeroandthe # flagisnotspecified,[Link],[Link]. (C99)A d o u b l e argumentrepresentinganinfinityisconvertedinoneofthestyles [ ]i n f or [ ]i n f i n i t y [Link] [ ]n a n or [ ]n a n ( ncharsequence) whichstyle,andthemeaningofany ncharsequence,[Link] 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,[Link] E conversionspecifierproducesa numberwith E insteadof e [Link],[Link],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),[Link],itistakenas1. Thestyleuseddependsonthevalueconvertedstyle e (or E )[Link] 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 [Link] pmightsufficedependingonthe implementation'sschemefordeterminingthedigittotheleftofthedecimalpointcharacter.)valuesoftype d o u b l e ,exceptthattrailingzerosmaybeomittediftheprecisioniszeroandthe # flagisnotspecified,nodecimalpointcharacterappears.
[Link]/wiki/C_Programming/Print_version
67/118
10/24/13
Theletters a b c d e f areusedfor a conversionandtheletters A B C D E F for A [Link] A conversionspecifierproducesanumberwith X and P insteadof x and p .Theexponentalwayscontainsatleastonedigit,andonlyasmanymoredigitsas [Link],theexponentiszero. A d o u b l e argumentrepresentinganinfinityorNaNisconvertedinthestyleofan f or F conversionspecifier.
c
Ifno l lengthmodifierispresent,theargumentshallbeapointertotheinitialelementofanarrayofcharactertype.(Nospecialprovisionsaremadeformultibytecharacters.)Charactersfromthearrayarewrittenupto(butnotincluding)the [Link],[Link],thearrayshallcontainanullcharacter. (C99)Ifan l lengthmodifierispresent,theargumentshallbeapointertotheinitialelementofanarrayof w c h a r _ t [Link](eachasifbyacalltothe w c r t o m b function,withthe conversionstatedescribedbyan m b s t a t e _ t objectinitializedtozerobeforethefirstwidecharacterisconverted)[Link](butnotincluding)the terminatingnullcharacter(byte).Ifnoprecisionisspecified,[Link],nomorethanthatmanycharacters(bytes)arewritten(includingshiftsequences,ifany),andthearrayshallcontain anullwidecharacterif,toequalthemultibytecharactersequencelengthgivenbytheprecision,[Link].(Redundantshift sequencesmayresultifmultibytecharactershaveastatedependentencoding.)
p
Theargumentshallbeapointerto v o i d .Thevalueofthepointerisconvertedtoasequenceofprintablecharacters,inanimplementationdefinedmanner.
n
A % [Link] % % . Ifaconversionspecificationisinvalid,[Link],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 [Link],andinthecaseoffixedpointconversionbythesourcevalueaswell.)Ifthenumberofsignificantdecimaldigitsismorethan D E C I M A L _ D I G butthesourcevalueisexactlyrepresentablewith D E C I M A L _ D I G digits,[Link],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,[Link] [Link],[Link],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 [Link] 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 [Link] 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 [Link] takesplacebetweenobjectsthatoverlap,[Link],notcountingtheterminatingnullcharacter.
References
1. Severalprogrammersrecommend"[Link]."[1]([Link] ([Link] tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5]([Link]
[Link]/wiki/C_Programming/Print_version
68/118
10/24/13
Beginningexercises
Variables
Naming
1. Canavariablenamestartwithanumber?can't 2. Canavariablenamestartwithatypographicalsymbolcan't(e.g.#,*,_)? 3. GiveanexampleofaCvariablenamethatwould not [Link]'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?
[Link]/wiki/C_Programming/Print_version
69/118
10/24/13
2. Isitpossibletoassignan int toa double? 1. Isthereversepossible?
Solution Thestandardwayofassigning3.14topiis:
d o u b l ep i ; p i = 3 . 1 4 ;
Sincepiisaconstant,[Link]:
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. [Link]"pi"toanothervariable,say"pi2": 1. Whatisthecorrectstatement? 2. Whatisthereverse?IsthisavalidCstatement(evenifitgivesincorrectresults)? 3. Whatifyouwantedtoassignaconstantvalue(like3.1415)to"pi2": [Link]? [Link]? 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 ; [Link]: 3 . 1 4 1 5=p i 2 ; isnotvalidsinceitisimpossibletoassignavaluetoaliteral.
SimpleI/O
Input
1. scanf()[Link]. 2. Writethescanf()functioncallthatwillreadintothevariable"var":
[Link]/wiki/C_Programming/Print_version
70/118
10/24/13
1. afloat 2. anint 3. adouble
Solution
Stringmanipulation
[Link],andprintsitsreverse. Solution Onepossiblesolutioncouldbe:
# i n c l u d e< s t d i o . h > # i n c l u d e< s t r i n g . h > i n tm a i n ( v o i d ) { c h a rs [ 8 1 ] ;/ /As t r i n go fu p t o8 0c h a r s+' \ 0 ' i n ti ; p u t s ( " P l e a s ew r i t eas t r i n g :" ) ; f g e t s ( s ,8 1 ,s t d i n ) ; p u t s ( " Y o u rs e n t e n c ei nr e v e r s e :" ) ; f o r( i =s t r l e n ( s ) 1 ;i> =0 ;i ) { i f( s [ i ]= =' \ n ' ) c o n t i n u e ;/ /d o n ' tw r i t en e w l i n e e l s e p u t c h a r ( s [ i ] ) ; } p u t c h a r ( ' \ n ' ) ; r e t u r n0 ; }
# i n c l u d e< s t d i o . h > i n tm a i n ( v o i d ) { c h a rs [ 8 1 ] ,w o r d [ 8 1 ] ; i n tn =0 ,i d x =0 ; p u t s ( " P l e a s ew r i t eas e n t e n c e : " ) ; f g e t s ( s ,8 1 ,s t d i n ) ; / *% sm a t c h e sas e q u e n c eo fn o n w h i t e s p a c ec h a r a c t e r ,w h i c hi sa * f a i rd e f i n i t i o no f" w o r d "i nt h i sc o n t e x t . *% nm a t c h e sn o t h i n g ,b u ts t o r e st h en u m b e ro fc h a r a c t e r st h a th a v e * b e e np r o c e s s e d .i . e .i fsi s" H e l l o ,W o r l d ! " ,t h e nw o r da n dn * w i l lb e" H e l l o , "a n d6r e s p e c t i v e l yi nt h ef i r s ti t e r a t i o n .I n * t h es e c o n di t e r a t i o nt h e yw i l lb e" W o r l d ! "a n d7( 6c h a r s+ * t h es p a c ei nf r o n to ft h ew o r d ) . * / w h i l e(s s c a n f ( & s [ i d x ] ," % s % n " ,w o r d ,& n )>0) { i d x+ =n ; p u t s ( w o r d ) ; }
[Link]/wiki/C_Programming/Print_version
71/118
10/24/13
r e t u r n0 ; }
Loops
[Link] n,so n=3wouldlooklike
* * * * * *
Solution Onepossiblesolution:
Solution Onepossiblesolution:
v o i ds i d e w a y s ( i n tn ) { i n tx , y ; f o r( y =0 ;y<n ;y + + ) { f o r( x =0 ;x< =y ;x + + ) p u t c h a r ( ' * ' ) ; p u t c h a r ( ' \ n ' ) ; } f o r( y =n 1 ;y>0 ;y ) { f o r( x =0 ;x<y ;x + + ) p u t c h a r ( ' * ' ) ; p u t c h a r ( ' \ n ' ) ; } }
orlikethis(allmath)
v o i ds i d e w a y s ( i n tn ) { i n ti = 0 , j = 0 ; f o r ( i = 1 ; i < 2 * n ; i + + ) { f o r ( j = 1 ; j < = ( n ( a b s ( n i ) ) ) ; j + + ) {
[Link]/wiki/C_Programming/Print_version
72/118
10/24/13
p r i n t f ( " * " ) ; } p r i n t f ( " \ n " ) ; } }
Solution Onepossiblesolution:
ProgramFlow
1.Buildaprogramwherecontrolpassesfrommaintofourdifferentfunctionswith4calls. [Link] [Link],so1goestofunction1,2goestofunction2,etc. 4.Havefunction1callfunctiona,whichcallsfunctionb,whichcallsfunctionc [Link],witharrowstoindicatewherecontrolgoes
Functions
1.Writeafunctiontocheckifanintegerisnegativethedeclarationshouldlooklikeboolis_positive(inti) [Link],soforexampletowhenyouuseit floata=raise_to_power(2,3)//agets8 floatb=raise_to_power(9,2)//bgets81 floatraise_to_power(floatf,intpower)//makethisyourdeclaration
Math
[Link].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
[Link]/wiki/C_Programming/Print_version
73/118
10/24/13
# i n c l u d e< m a t h . h > / /f o rt h es q u a r er o o tf u n c t i o ns q r t ( ) # i n c l u d e< s t d i o . h > i n ti s _ p r i m e ( i n tn ) ; i n tm a i n ( ) { p r i n t f ( " W r i t ea ni n t e g e r :" ) ; i n tv a r ; s c a n f ( " % d " ,& v a r ) ; i f( i s _ p r i m e ( v a r ) = = 1 ){ p r i n t f ( " Ap r i m e \ n " ) ; }e l s e{ p r i n t f ( " N o tap r i m e \ n " ) ; } r e t u r n1 ; } i n ti s _ p r i m e ( i n tn ) { i n tx ; i n ts q =s q r t ( n ) + 1 ; / /C h e c k i n gt h et r i v i a lc a s e sf i r s t i f(n<2) r e t u r n0 ; i f(n= =2| |n= =3) r e t u r n1 ; / /C h e c k i n gi fni sd i v i s i b l eb y2o ro d dn u m b e r sb e t w e e n3a n dt h e / /s q u a r er o o to fn . i f(n%2= =0) r e t u r n0 ; f o r( x =3 ;x< =s q ;x+ =2 ) { i f(n%x= =0) r e t u r n0 ; } r e t u r n1 ; }
Recursion
Mergesort [Link],andsortitrecursivelyusingtheMergesortalgorithm. Themergesortalgorithmisarecursivealgorithm. sortingaoneelementarrayiseasy. sortingtwooneelementarrays,[Link],andcomparestheheadofthelist,andwhicheverheadissmaller,thiselementisputonthesortedlistandtheheadofthatlistis tickedoff,[Link],andtheotherlististhencopiedontotheendofthesortedlist. therecursionoccurs,becausemergingtwooneelementarraysproducesonetwoelementsortedarray,whichcanbemergedwithanothertwoelementsortedarrayproducedthesameway.Thisproducesasorted4elementarray,andthesameapplies foranother4elementsortedarray. sothebasicmergesort,istocheckthesizeoflisttobesorted,andifitisgreaterthanone,dividethearrayintotwo,[Link],mergethetwohalvesinatemporaryspaceofequalsize,andthencopy backthefinalsortedarrayontotheoriginalarray. Solution Onepossiblesolution,afterreadingonlinedescriptionsofrecursivemergesort,[Link]:
/ /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
[Link]/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 ]){
[Link]/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
[Link]/wiki/C_Programming/Print_version
76/118
10/24/13
Binaryheaps 2. Binaryheaps: Abinarymaxheaporminheap,isanorderedstructurewheresomenodesareguaranteedgreaterthanothernodes,[Link],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,[Link]>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
[Link]/wiki/C_Programming/Print_version
77/118
10/24/13
apriorityqueueallowselementstobeinsertedwithapriority,andextractedaccordingtopriority.(Thiscanhappenusefully,iftheelementhasapairedstructure,onepartisthekey,[Link],itisjustamechanism forsorting). EXERCISE:Usingtheabovetechniqueofinsertback/challengeparent,anddeletefront/lasttofront/deferhigherchild,implementeitherheapsortorapriorityqueue. Dijsktra'salgorithm Dijsktra'[Link],acurrent distancetostartnode,[Link],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 [Link]. youcanusethe"driver",[Link]"reuse",whichisencouragedingeneral. anadvantageofreuseislesswritingtime,debuggingtime,testingtime. theconceptofpartitionexchangeisthatapartitionelementis(randomly)selected,andeverythingthatneedssortedisputinto3equivalance classes:thoseelementslessthanthepartitionvalue,thepartitionelement,andeverythingabove(andequalto)thepartitionelement. [Link]. However,wherethepartitionelementshouldbeusingtheoriginalarrayspaceisnotknown. Thisisusuallyimplementedwithputtingthepartitionontheendofthearraytobesorted,andthenputtingtwopointers,oneatthestartofthearray, andoneattheelementnexttothepartitionelement,andrepeatedlyscanningtheleftpointerright,andtherightpointerleft. theleftscanstopswhenanelementequaltoorgreaterthanthepartitionisfound,andtherightscanstopsforasmallerelementthanthepartitionvalue, andtheseareswapped,whichusesthetemporaryextraspace. theleftscanwillalwaysstopifitreachesthepartitionelement,whichisthelastelementthismeanstheentirearrayislessthanpartitionvalue. therightscancouldreachthefirstelement,iftheentirearrayisgreaterthanthepartition,andthisneedstobetestedfor,elsethescandoesn'tstop. [Link] shouldoccurbeforeswapping,otherwisetherightpointermaybeswappingalessthanpartitionelementpreviouslyscannedbytheleftpointer. finally,thepartitionelementneedstobeputbetweentheleftandrightpartitions,oncethepointerscross. Atpointercrossing,theleftpointermaybestoppedatthepartitionelement'slastpositioninthearray,andtherightpointernotprogressedpastthe [Link]. iftherightpointerischosentoswapwiththepartition,thenanincorrectstateresultswherethelastelementoftheleftarraybecomeslessthanthepartitionelementvalue. iftheleftpointerischosentoswapwiththepartition,thentheleftarraywillbelessthanthepartition,andpartitionwillhaveswappedwithanelementwithvaluegreaterthanthepartitionorthepartitionitself.
[Link]/wiki/C_Programming/Print_version
78/118
10/24/13
Thecornercaseofquicksortinga2element outoforderarrayhastobeexamined. Theleftpointerstopsonthefirst [Link] outoforderelement,[Link]'sfirstelement, andthetwoelementsarenow inorder. Inthecaseofa2element inorderarray,theleftmostpointerskipsthefirstelementwhichislessthanthepartition,[Link] [Link],sotheinorderingispreserved. Afterdoingaswap,theleftpointershouldbeincrementedandrightpointerdecremented,sothesamepositionsaren'tscannedagain,becauseanendlessloopcanresult(possiblywhentheleftpointerexitswhentheelementisequaltoorgreater thanthepartition,andtherightelementisequaltothepartitionvalue).Oneimplementation,Sedgewick,startsthepointerswiththeleftpointerminusoneandrightpointer theplusonetheintendedinitialscanpositions,andusethepreincrementandpredecrementoperatorse.g.(++i,i). Solution Onepossiblesolution,[Link],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 ) ;
[Link]/wiki/C_Programming/Print_version
79/118
10/24/13
q s o r t s i m p (a ,e l e m _ s z ,p ,c m p ) ; q s o r t s i m p (a + ( p + 1 ) * e l e m _ s z ,e l e m _ s z ,l e n-p1 ,c m p) ; } }
/ / / * N a m e :w o r d s _ q u i c k s o r t . c A u t h o r :a n o n y m o u s V e r s i o n : C o p y r i g h t : D e s c r i p t i o n:q u i c ks o r tt h ew o r d si nm o b yd i c ki nC ,A n s i s t y l e = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / # i n c l u d e< s t d i o . h > # i n c l u d e< s t d l i b . h > # i n c l u d e< c t y p e . h > # i n c l u d e< s t r i n g . h > # i n c l u d e" q s o r t s i m p . h " v o i dp r i n t A r r a y ( c o n s tc h a r *a [ ] ,i n tn ){ i n ti ; f o r ( i = 0 ;i<n ;+ + i ){ i f ( i ! = 0& &i %5= =0 ){ p r i n t f ( " \ n " ) ; } i f( i % 1 0 0 0 0 0 0= = 0 ){ f p r i n t f ( s t d e r r , " p r i n t e d% dw o r d s \ n " ,i ) ; } p r i n t f ( " % s " ,a [ i ] ) ; } p r i n t f ( " \ n " ) ; } c o n s ti n tM A X C H A R S = 2 5 0 ; c h a r* *w o r d l i s t = 0 ; i n tn w o r d s = 0 ; i n tr e m a i n i n g _ b l o c k ; c o n s ts i z e _ tN W O R D S _ P E R _ B L O C K=1 0 0 0 ; / / c o n s tc h a r *s p a c e s = "\ t \ n \ r " ; / / i n l i n ei s s p a c e ( c o n s tc h a rc h ){ / / i n ti = 0 ; / / w h i l e ( s p a c e s [ i ] ! = ' \ 0 ' ){ / / i f ( s p a c e s [ i + + ]= =c h ) / / r e t u r n1 ; / / } / / r e t u r n0 ; / / } v o i df r e e M e m ( ){ i n ti=n w o r d s ; w h i l e ( i>0){ f r e e ( w o r d l i s t [ i ] ) ; } f r e e ( w o r d l i s t ) ; } s t a t i cc h a r*f n a m e = " ~ / D o w n l o a d s / b o o k s / p g 2 7 0 1 m o b y d i c k . t x t " ; v o i dg e t W o r d s ( ){ c h a rb u f f e r [ M A X C H A R S ] ; F I L E *f=f o p e n ( f n a m e , " r " ) ; i n ts t a t e = 0 ; i n tc h ; i n ti ; w h i l e( ( c h = f g e t c ( f ) ) ! = E O F ){ i f( i s a l n u m ( c h )& &s t a t e = = 0 ){ s t a t e = 1 ; i = 0 ; b u f f e r [ i + + ] = c h ; }e l s ei f( i s a l n u m ( c h ) & &i<M A X C H A R S 1 ){ b u f f e r [ i + + ] = c h ; }e l s ei f( s t a t e= =1 ){ s t a t e= 0 ; b u f f e r [ i + + ] =' \ 0 ' ; c h a r *d y n b u f=m a l l o c ( i ) ; i n tj ; f o r ( j = 0 ;j<i ;+ + j ){
[Link]/wiki/C_Programming/Print_version
80/118
10/24/13
d y n b u f [ j ]=b u f f e r [ j ] ; } i = 0 ; i f( w o r d l i s t= =0){
w o r d l i s t=c a l l o c ( N W O R D S _ P E R _ B L O C K ,s i z e o f ( c h a r * ) ) ; r e m a i n i n g _ b l o c k=N W O R D S _ P E R _ B L O C K ; }e l s ei f(r e m a i n i n g _ b l o c k= =0 ){ w o r d l i s t=r e a l l o c ( w o r d l i s t ,( N W O R D S _ P E R _ B L O C K+n w o r d s ) *s i z e o f ( c h a r * ) ) ; r e m a i n i n g _ b l o c k=N W O R D S _ P E R _ B L O C K ; f p r i n t f ( s t d e r r , " a l l o c a t e db l o c k% d,n w o r d s=% d \ n " ,r e m a i n i n g _ b l o c k ,n w o r d s ) ; } w o r d l i s t [ n w o r d s + + ] =d y n b u f ; r e m a i n i n g _ b l o c k ; } } f c l o s e ( f ) ; } v o i dt e s t P r i n t A r r a y ( ){ i n ti ; f o r ( i = 0 ;i<n w o r d s ; + + i ){ p r i n t f ( " % s|" ,w o r d l i s t [ i ] ) ; } p u t c h a r ( ' \ n ' ) ; p r i n t f ( " s t o r e d% dw o r d s .\ n " , n w o r d s ) ; } i n tc m p _ s t r _ 1 (v o i d *a ,v o i d* b ){ i n tr=s t r c a s e c m p (* ( ( c h a r * * ) a ) , * ( ( c h a r * * ) b ) ) ; r e t u r nr ; } i n tm a i n ( i n ta r g c ,c h a r *a r g v [ ] ){ i f( a r g c>1 ){ f n a m e=a r g v [ 1 ] ; } g e t W o r d s ( ) ; t e s t P r i n t A r r a y ( ) ; q s o r t s i m p ( w o r d l i s t ,s i z e o f ( c h a r * ) ,n w o r d s ,& c m p _ s t r _ 1 ) ; t e s t P r i n t A r r a y ( ) ; s h u t d o w n _ q s o r t s i m p ( ) ; f r e e M e m ( ) ; p u t s ( " ! ! ! H e l l oW o r l d ! ! ! " ) ;/ *p r i n t s! ! ! H e l l oW o r l d ! ! !* / r e t u r nE X I T _ S U C C E S S ; }
IndepthCideas Arrays
ArraysinCacttostorerelateddataunderasinglevariablenamewithanindex,alsoknownasa subscript .[Link],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.
[Link]/wiki/C_Programming/Print_version
81/118
10/24/13
Ifwewishtoinitializeaswedeclare,wewrite:
i n tp o i n t [ 6 ] = { 0 , 0 , 1 , 0 , 0 , 0 } ;
Thoughwhenthearrayisinitializedasinthiscase,thearraydimensionmaybeomitted,andthearraywillbeautomaticallysizedtoholdtheinitialdata:
i n tp o i n t [ ] = { 0 , 0 , 1 , 0 , 0 , 0 } ;
Thisisveryusefulinthatthesizeofthearraycanbecontrolledbysimplyaddingorremovinginitializerelementsfromthedefinitionwithouttheneedtoadjustthedimension. Ifthedimensionisspecified,butnotallelementsinthearrayareinitialized,[Link],especiallywhenwehaveverylargearrays.
i n tn u m b e r s [ 2 0 0 0 ] = { 2 4 5 } ;
Theaboveexamplesetsthefirstvalueofthearrayto245,andtherestto0. Ifwewanttoaccessavariablestoredinanarray,forexamplewiththeabovedeclaration,thefollowingcodewillstorea1inthevariable x
i n tx ; x=p o i n t [ 2 ] ;
Duringprogramexecution,[Link][1].Toalleviateindexingproblems,thesizeof()expressioniscommonlyusedwhen codingloopsthatprocessarrays.
i n ti x ; s h o r ta n A r r a y [ ] ={3 ,6 ,9 ,1 2 ,1 5} ; f o r( i x = 0 ;i x <( s i z e o f ( a n A r r a y ) / s i z e o f ( s h o r t ) ) ;+ + i x ){ D o S o m e t h i n g W i t h ( " % d " ,a n A r r a y [ i x ]) ; }
Toaccess/modifyavalueinthisarrayweneedtwosubscripts:
c h a rc h ; c h=t w o _ d [ 2 ] [ 4 ] ;
or
t w o _ d [ 0 ] [ 0 ]=' x ' ;
Similarly,amultidimensionalarraycanbeinitializedlikethis:
i n tt w o _ d [ 2 ] [ 3 ]={ {5 ,2 ,1} , {6 ,7 ,8} } ;
[Link]/wiki/C_Programming/Print_version
82/118
10/24/13
Theamountofcolumnsmustbeexplicitlystatedhowever,thecompilerwillfindtheappropriateamountofrowsbasedontheinitializerlist. Therearealsoweirdnotationspossible:
i n ta [ 1 0 0 ] ; i n ti=0 ; i f( a [ i ] = = i [ a ] ) { p r i n t f ( " H e l l ow o r l d ! \ n " ) ; }
a[i]andi[a]refertothesamelocation.(ThisisexplainedlaterinthenextChapter.)
Strings
Chasnostringhandlingfacilitiesbuiltinconsequently,[Link], [Link],tostorethestring"Merkkijono",wewouldwrite
c h a rs t r i n g [ ]=" M e r k k i j o n o " ;
String"Merkkijono"storedinmemory
or
c h a rs t r i n g [ ]={ ' M ' ,' e ' ,' r ' ,' k ' ,' k ' ,' i ' ,' j ' ,' o ' ,' n ' ,' o ' ,' \ 0 ' } ;
Whilestringsmayalsospanmultiplelinesbyputtingthebackslashcharacterattheendoftheline,thismethodisdeprecated. Thereisausefullibraryofstringhandlingroutineswhichyoucanusebyincludinganotherheaderfile.
# i n c l u d e< s t r i n g . h > / / n e wh e a d e rf i l e
Thisstandardstringlibrarywillallowvarioustaskstobeperformedonstrings,andisdiscussedintheStringschapter.
Pointersandarrays
A pointerisavaluethatdesignatestheaddress(i.e.,thelocationinmemory),[Link]: Howtodeclarethem Howtoassigntothem Howtoreferencethevaluetowhichthepointerpoints(knownas dereferencing)and Howtheyrelatetoarrays We'llalsodiscusstherelationshipofpointerswithtextstringsandthemoreadvancedconceptoffunctionpointers. [Link]'* '.Pointerscanreferenceanydatatype,evenfunctions. ThevastmajorityofarraysinCaresimplelists,alsocalled"1dimensionalarrays".Wewillbrieflycovermultidimensionalarraysinalaterchapter.
Declaringpointers
Considerthefollowingsnippetofcodewhichdeclarestwopointers:
[Link] 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 . } ;
[Link]/wiki/C_Programming/Print_version
83/118
10/24/13
5 . J 2 6 . i n t *p ; y S t r u c t*p A n I t e m 7 . s t r u c tM ;
a r 1 a r 2 1 .l o n g * v ,v ; 3 2 . i n t * *p ;
Assigningvaluestopointers
Sofarwe'[Link],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. [Link]()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,[Link],the [Link].
[Link]/wiki/C_Programming/Print_version
84/118
10/24/13
Pointerdereferencing
Toaccessavaluetowhichapointerpoints,the * [Link],the > [Link]'sashortexample.
i n t c ,d ; i n t * p j ; s t r u c tM y S t r u c ta s t r u c t ; s t r u c tM y S t r u c t* b b ; c =1 0 ; p j =& c ; d =* p j ; p j =& d ; * p j=1 2 ; / *p jp o i n t st oc* / / *di sa s s i g n e dt h ev a l u et ow h i c hp jp o i n t s ,1 0* / / *n o wp o i n t st od* / / *di sn o w1 2* / Thepointerp pointstothevariablea .
Theexpression b b > m _ a N u m b e r isentirelyequivalentto ( * b b ) . m _ a N u m b e r .Theybothaccessthe m _ a N u m b e r elementofthestructurepointedtoby b b .Thereisonemorewayofdereferencingapointer,whichwillbediscussedinthefollowingsection. Whendereferencingapointerthatpointstoaninvalidmemorylocation,[Link] tryingtodereferenceit. Cisknownforgivingyoujustenoughropetohangyourself,[Link],that [Link],evenif99executionsallowyourprogramtorunwithoutfault,that100thexecutionmaybethetimewhenyour"memorypilfering"iscaughtby [Link]! Thedeclaration v o i d* s o m e P o i n t e r ; [Link],[Link] validwith v o i d* pointers.
PointersandArrays
Uptonow,we'[Link]: [Link],itpointstothefirstelementofthearray. Apointercanbeindexedlikeanarrayname. [Link],[Link] [Link]'[Link],thecalltocalloc()effectivelyallocatesanarrayofstructMyStructitems.
f l o a tK r a z y F u n c t i o n (s t r u c tM y S t r u c t* p a r m 1 ,i n tp 1 s i z e ,i n tb b) { i n ti x ;/ / d e c l a r i n ga ni n t e g e rv a r i a b l e / / f o r( i x = 0 ;i x < p 1 s i z e ;i x + + ){ i f( p a r m 1 [ i x ] . m _ a N u m b e r= =b b) r e t u r np a r m 1 [ i x ] . n u m 2 ; } r e t u r n0 . 0 f ; } / *. . .* / s t r u c tM y S t r u c tm y A r r a y [ 4 ] ; # d e f i n eM Y _ A R R A Y _ S I Z E( s i z e o f ( m y A r r a y ) / s i z e o f ( * m y A r r a y ) ) f l o a tv 3 ; s t r u c tM y S t r u c t* s e c o n d A r r a y ; i n t s o m e S i z e ; i n t i x ; / *i n i t i a l i z a t i o no fm y A r r a y. . .* / v 3=K r a z y F u n c t i o n (m y A r r a y ,M Y _ A R R A Y _ S I Z E ,4) ; / *. . .* / s e c o n d A r r a y=c a l l o c (s o m e S i z e ,s i z e o f ( m y A r r a y )) ; f o r( i x = 0 ;i x < s o m e S i z e ;i x + + ){ s e c o n d A r r a y [ i x ] . m _ a N u m b e r=i x* 2 ; s e c o n d A r r a y [ i x ] . n u m 2=. 3 0 4*i x*i x ; }
/ *t w oe q u i v a l e n tf u n c t i o nd e f i n i t i o n s* / i n tL i t t l e F u n c t i o n (i n t* p a r a m N) ;
[Link]/wiki/C_Programming/Print_version
85/118
10/24/13
i n tL i t t l e F u n c t i o n (i n tp a r a m N [ ]) ;
Let'[Link],butwedon'[Link] [Link]'ssomeapplicablecode:
f l o a t l i n e a r A [ 3 0 ] ; f l o a t* A [ 6 ] ; A [ 0 ]=l i n e a r A ; A [ 1 ]=l i n e a r A+5 ; A [ 2 ]=l i n e a r A+1 1 ; A [ 3 ]=l i n e a r A+1 5 ; A [ 4 ]=l i n e a r A+2 1 ; A [ 5 ]=l i n e a r A+2 5 ; A [ 3 ] [ 2 ]=3 . 6 6 ; A [ 3 ] [ 3 ]=1 . 4 4 ; / * 5-0=5e l e m e n t si nr o w * / / *1 1-5=6e l e m e n t si nr o w * / / *1 5-1 1=4e l e m e n t si nr o w* / / *2 1-1 5=6e l e m e n t s * / / *2 5-2 1=4e l e m e n t s * / / *3 0-2 5=5e l e m e n t s * / / *a s s i g n s3 . 6 6t ol i n e a r A [ 1 7 ] ; * / / *r e f e r st ol i n e a r A [ 1 2 ] ; n e g a t i v ei n d i c e sa r es o m e t i m e su s e f u l .B u ta v o i du s i n gt h e ma sm u c ha sp o s s i b l e .* /
PointersinFunctionArguments
[Link],[Link] circumstancetoobtainapointervalue,[Link],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 [Link] 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 [Link] 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) {
[Link]/wiki/C_Programming/Print_version
86/118
10/24/13
/ * d os o m es t u f f. . .* / r e t u r n0 ; } i n tF u n c t T w o (s t r u c ts o m e S t r u c t* p S t r u c t ,i n t* m V a l u e) { i n tj ; l o n g A n A r r a y [ 2 5 ] ; l o n g* p A A ; p A A=& A n A r r a y [ 1 3 ] ; j=F u n c t O n e (p S t r u c t ,* m V a l u e ,p A A) ; r e t u r nj ; }
PointersandTextStrings
Historically,textstringsinChavebeenimplementedasarraysofcharacters,withthelastbyteinthestringbeingazero,orthenullcharacter'\0'.[Link] [Link]"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 [Link]('\0')tackedontotheendofthestringafterthe'd'[Link]:
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
[Link]'sanexamplethatusesafunctionpointer,andavoid*pointertoimplementwhat's [Link] D o S o m e t h i n g N i c e functioninvokesacallersuppliedfunction T a l k J i v e [Link] 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* /
[Link]/wiki/C_Programming/Print_version
87/118
10/24/13
} s t a t i cD a t a I N e e d s i l l y S t u f f={B L U E ," W h a t c h at a l k i n' b o u tW i l l i s ? "} ; / *. . .* / D o S o m e t h i n g N i c e (4 1 ,& T a l k J i v e , & s i l l y S t u f f) ;
SomeversionsofCmaynotrequireanampersandprecedingthe T a l k J i v e argumentinthe D o S o m e t h i n g N i c e [Link] M y F u n c t i o n T y p e type,eventhoughthefunctionsignatureexacly matchesthatofthetypedef. [Link] [Link],andstaticvariableofthetypeofthefirststructure,containingtheaddressesofthefunctionsthatare [Link]/Ofunctionsarecalled. [Link],[Link] [Link] [Link],theappropriatefunctioniscalledthroughafunctionpointerinthecurrentstate.
PracticaluseoffunctionpointersinC
[Link]:
# 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 ) {
[Link]/wiki/C_Programming/Print_version
88/118
10/24/13
r e t u r n( i j ) ; } i n tm u l ( i n ti ,i n tj ) { r e t u r n( i * j ) ; } i n td i v ( i n ti ,i n tj ) { r e t u r n( i / j ) ; }
Functionpointersmaybeusedtocreateastructmemberfunction:
t y p e d e fs t r u c t { i n t( * o p e n ) ( v o i d ) ; v o i d( * c l o s e ) ( v o i d ) ; i n t( * r e g i s t e r ) ( v o i d ) ; }d e v i c e ; i n tm y _ d e v i c e _ o p e n ( v o i d ) { / *. . .* / } v o i dm y _ d e v i c e _ c l o s e ( v o i d ) { / *. . .* / } v o i dr e g i s t e r _ d e v i c e ( v o i d ) { / *. . .* / } d e v i c ec r e a t e ( v o i d ) { d e v i c em y _ d e v i c e ; m y _ d e v i c e . o p e n=m y _ d e v i c e _ o p e n ; m y _ d e v i c e . c l o s e=m y _ d e v i c e _ c l o s e ; m y _ d e v i c e . r e g i s t e r=r e g i s t e r _ d e v i c e ; m y _ d e v i c e . r e g i s t e r ( ) ; r e t u r nm y _ d e v i c e ; }
Usetoimplementthispointer(followingcodemustbeplacedinlibrary).
s t a t i cs t r u c td e v i c e _ d a t a { / *. . .h e r eg o e sd a t ao fs t r u c t u r e. . .* / } ; s t a t i cs t r u c td e v i c e _ d a t ao b j ; t y p e d e fs t r u c t { i n t( * o p e n ) ( v o i d ) ; v o i d( * c l o s e ) ( v o i d ) ; i n t( * r e g i s t e r ) ( v o i d ) ; }d e v i c e ; s t a t i cs t r u c td e v i c e _ d a t ac r e a t e _ d e v i c e _ d a t a ( v o i d ) { s t r u c td e v i c e _ d a t am y _ d e v i c e _ d a t a ; / *. . .h e r eg o e sc o n s t r u c t o r. . .* / r e t u r nm y _ d e v i c e _ d a t a ; } / *h e r eIo m i tt h em y _ d e v i c e _ o p e n ,m y _ d e v i c e _ c l o s ea n dr e g i s t e r _ d e v i c ef u n c t i o n s* / d e v i c ec r e a t e _ d e v i c e ( v o i d ) { d e v i c em y _ d e v i c e ; m y _ d e v i c e . o p e n=m y _ d e v i c e _ o p e n ; m y _ d e v i c e . c l o s e=m y _ d e v i c e _ c l o s e ; m y _ d e v i c e . r e g i s t e r=r e g i s t e r _ d e v i c e ; m y _ d e v i c e . r e g i s t e r ( ) ; r e t u r nm y _ d e v i c e ; }
Examplesofpointerconstructs
Belowaresomeexampleconstructswhichmayaidincreatingyourpointer.
[Link]/wiki/C_Programming/Print_version
89/118
10/24/13
i n ti ; / /i n t e g e rv a r i a b l e' i ' i n t* p ; / /p o i n t e r' p 't oa ni n t e g e r i n ta [ ] ; / /a r r a y' a 'o fi n t e g e r s i n tf ( ) ; / /f u n c t i o n' f 'w i t hr e t u r nv a l u eo ft y p ei n t e g e r i n t* * p p ; / /p o i n t e r' p p 't oap o i n t e rt oa ni n t e g e r i n t( * p a ) [ ] ; / /p o i n t e r' p a 't oa na r r a yo fi n t e g e r i n t( * p f ) ( ) ; / /p o i n t e r' p f 't oaf u n c t i o nw i t hr e t u r nv a l u ei n t e g e r i n t* a p [ ] ; / /a r r a y' a p 'o fp o i n t e r st oa ni n t e g e r i n t* f p ( ) ; / /f u n c t i o n' f p 'w h i c hr e t u r n sap o i n t e rt oa ni n t e g e r i n t* * * p p p ; / /p o i n t e r' p p p 't oap o i n t e rt oap o i n t e rt oa ni n t e g e r i n t( * * p p a ) [ ] ;/ /p o i n t e r' p p a 't oap o i n t e rt oa na r r a yo fi n t e g e r s i n t( * * p p f ) ( ) ;/ /p o i n t e r' p p f 't oap o i n t e rt oaf u n c t i o nw i t hr e t u r nv a l u eo ft y p ei n t e g e r i n t* ( * p a p ) [ ] ;/ /p o i n t e r' p a p 't oa na r r a yo fp o i n t e r st oa ni n t e g e r i n t* ( * p f p ) ( ) ;/ /p o i n t e r' p f p 't of u n c t i o nw i t hr e t u r nv a l u eo ft y p ep o i n t e rt oa ni n t e g e r i n t* * a p p [ ] ; / /a r r a yo fp o i n t e r s' a p p 't h a tp o i n tt op o i n t e r st oi n t e g e rv a l u e s i n t( * a p a [ ] ) [ ] ; / /a r r a yo fp o i n t e r s' a p a 't oa r r a y so fi n t e g e r s i n t( * a p f [ ] ) ( ) ; / /a r r a yo fp o i n t e r s' a p f 't of u n c t i o n sw i t hr e t u r nv a l u e so ft y p ei n t e g e r i n t* * * f p p ( ) ; / /f u n c t i o n' f p p 'w h i c hr e t u r n sap o i n t e rt oap o i n t e rt oap o i n t e rt oa ni n t i n t( * f p a ( ) ) [ ] ; / /f u n c t i o n' f p a 'w i t hr e t u r nv a l u eo fap o i n t e rt oa r r a yo fi n t e g e r s i n t( * f p f ( ) ) ( ) ; / /f u n c t i o n' f p f 'w i t hr e t u r nv a l u eo fap o i n t e rt of u n c t i o nw h i c hr e t u r n sa ni n t e g e r
sizeof
Thesizeofoperatorisoftenusedtorefertothesizeofastaticarraydeclaredearlierinthesamefunction. Tofindtheendofanarray(examplefromwikipedia:Bufferoverflow):
/ *b e t t e r . c-d e m o n s t r a t e so n em e t h o do ff i x i n gt h ep r o b l e m* / # i n c l u d e< s t d i o . h > # i n c l u d e< s t r i n g . h > i n tm a i n ( i n ta r g c ,c h a r* a r g v [ ] ) { c h a rb u f f e r [ 1 0 ] ; i f( a r g c<2 ) { f p r i n t f ( s t d e r r ," U S A G E :% ss t r i n g \ n " ,a r g v [ 0 ] ) ; r e t u r n1 ; } s t r n c p y ( b u f f e r ,a r g v [ 1 ] ,s i z e o f ( b u f f e r ) ) ; b u f f e r [ s i z e o f ( b u f f e r )-1 ]=' \ 0 ' ; r e t u r n0 ; }
Toiterateovereveryelementofanarray,use
# d e f i n eN U M _ E L E M ( x )( s i z e o f( x )/s i z e o f( * ( x ) ) ) f o r (i=0 ;i<N U M _ E L E M ( a r r a y ) ;i + +) { / *d os o m e t h i n gw i t ha r r a y [ i ]* / ; }
[Link]/wiki/C_Programming/Print_version
90/118
10/24/13
i n tm a i n ( i n ta r g c ,c h a r* a r g v [ ] ) { i n tl e f t _ a r r a y [ ]={1 ,2 ,3} ; i n tr i g h t _ a r r a y [ ]={1 0 ,9 ,8 ,7 ,6 ,5 ,4 ,3 ,2 ,1} ; i n tt h e _ s u m=s u m (l e f t _ a r r a y) ; p r i n t f (" t h es u mo fl e f t _ a r r a yi s :% d " ,t h e _ s u m) ; t h e _ s u m=s u m (r i g h t _ a r r a y) ; p r i n t f (" t h es u mo fr i g h t _ a r r a yi s :% d " ,t h e _ s u m) ; r e t u r n0 ; }
ExternalLinks
CReferenceCard(ANSI)([Link] "CommonPointerPitfalls"([Link] "Furtherinsightsintosize_t"([Link] "PointerFunwithBinky"
Memorymanagement
InC,[Link],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 ) ;
[Link]/wiki/C_Programming/Print_version
91/118
10/24/13
Recall a r r a y canbeconsideredapointerwhichweuseasanarray.Wespecifythelengthofthisarrayis10 i n t [Link] a r r a y [ 0 ] ,nineotherintegershavespacetobestoredconsecutively. [Link] declareapointer,andinvoke m a l l o c whenwewishtomakespacefortheelementsinourarray, or,wecantell m a l l o c [Link]. Wealsoneedtoknowhowmuchaninttakesupinmemoryinordertomakeroomforitfortunatelythisisnotdifficult,wecanuseC'sbuiltin s i z e o f [Link],if s i z e o f ( i n t ) yields4,thenone i n t [Link], 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,[Link] sureyoudoso,too.(Seelaterthefunction m e m s e t forasimplemethod.) Itisnotnecessarytoimmediatelycall m a l l o c [Link] 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 [Link],wecanconceivablyrunoutofmemory!Inthiscase, m a l l o c willreturn N U L L .Inordertostoptheprogramcrashingfromhavingno morememorytouse,oneshouldalwayscheckthatmallochasnotreturned N U L L beforeattemptingtousethememorywecandothisby
i n t* p t=m a l l o c ( 3*s i z e o f ( i n t ) ) ; i f ( p t= =N U L L ) { f p r i n t f ( s t d e r r ," O u to fm e m o r y ,e x i t i n g \ n " ) ; e x i t ( 1 ) ; }
Thec a l l o c function
The c a l l o c [Link] 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 [Link],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) ;
[Link]/wiki/C_Programming/Print_version
92/118
10/24/13
The r e a l l o c functionchangesthesizeoftheobjectpointedtoby p t r tothesizespecifiedby s i z e .[Link],thevalueofthenewlyallocatedportionof [Link] p t r isanullpointer,the r e a l l o c functionbehaveslikethe m a l l o c [Link],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,[Link],theobjectpointedtoby p t r [Link] s i z e iszeroand p t r isnotanullpointer,[Link] 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 [Link],whichcouldresultinaneventualmemory [Link] f r e e [Link] 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 [Link].
t y p e d e fs t r u c tB S T N o d e { i n tv a l u e ; s t r u c tB S T N o d e *l e f t ; s t r u c tB S T N o d e *r i g h t ; }B S T N o d e ; / /L a t e r :. . . B S T N o d e *t e m p=( B S T N o d e * )c a l l o c ( 1 ,s i z e o f ( B S T N o d e ) ) ; t e m p > l e f t=( B S T N o d e * )c a l l o c ( 1 ,s i z e o f ( B S T N o d e ) ) ; / /L a t e r :. . . f r e e ( t e m p ) ;/ /W R O N G !d o n ' td ot h i s !
Don'tfreeundefinedpointers
Furthermore,using f r e e whenthepointerinquestionwasneverallocatedinthefirstplaceoftencrashesorleadstomysteriousbugsfurtheralong. Toavoidthisproblem,[Link] m a l l o c atthepointtheyaredeclared(asinmostexamplesinthischapter),orsetthemto N U L L whentheyaredeclared(asinthe"delayedallocation"exampleinthis chapter). [17]
References
1. Severalprogrammersrecommend"[Link]."[1]([Link] ([Link] tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5]([Link] 3. [[Link] 4. "CodingConventionsforC++andJava"([Link] Thisdeliberatechoicewasmadebecausealigningthoseprettystarsisalargewasteoftimeanddiscouragesthemaintenanceofinlinecomments.", 5. wiki:BigBlocksOfAsterisks,"Codecraft"([Link] 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"([Link]
Strings
A [Link]: ' \ 0 ' .So,astringwiththecontents,say, " a b c " hasfourcharacters: ' a ' , ' b ' , ' c ' ,andtheterminatingnullcharacter. Theterminatingnullcharacterhasthevaluezero.
[Link]/wiki/C_Programming/Print_version
93/118
10/24/13
Syntax
InC,stringconstants(literals)aresurroundedbydoublequotes("),e.g."Helloworld!"andarecompiledtoanarrayofthespecified c h a r valueswithanadditionalnullterminatingcharacter(0valued)[Link] 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)[Link]
w c h a r _ t* p=L " H e l l o w o r l d ! " ;
Characterencodings
Whatcharacterencodingthe c h a r and w c h a r _ t representisnotspecifiedbytheCstandard,[Link] [Link]. Therearethreemajortypesofencodings: [Link].Thereisalimitof255differentcharactersplusthezeroterminationcharacter. Variablelength c h a r strings,[Link] c h a r basedarrays.TheseencodingsarenormallyASCIIbasedandexamplesareUTF8orShiftJIS. [Link] w c h a r _ t values.UTF16isthemostcommonsuchencoding,anditisalsovariablelength,meaningthatacharactercanbetwo w c h a r _ t .
Themorecommonlyusedstringfunctions
Theninemostcommonlyusedfunctionsinthestringlibraryare:
s t r c a t concatenatetwostrings
[Link]/wiki/C_Programming/Print_version
94/118
10/24/13
s t r c h r stringscanningoperation s t r c m p comparetwostrings s t r c p y copyastring s t r l e n getstringlength s t r n c a t concatenateonestringwithpartofanother s t r n c m p comparepartsoftwostrings s t r n c p y copypartofastring s t r r c h r stringscanningoperation
The s t r c a t function
c h a r* s t r c a t ( c h a r*r e s t r i c ts 1 ,c o n s tc h a r*r e s t r i c ts 2 ) ;
Somepeoplerecommendusing s t r n c a t ( ) or s t r l c a t ( ) insteadofstrcat,inordertoavoidbufferoverflow. The s t r c a t ( ) functionshallappendacopyofthestringpointedtoby s 2 (includingtheterminatingnullbyte)totheendofthestringpointedtoby s 1 .Theinitialbyteof s 2 overwritesthenullbyteattheendof s 1 .Ifcopyingtakesplacebetweenobjectsthat overlap,[Link] s 1 . [Link](s 1 )havethespaceneededtostorebothstrings. Example:
# i n c l u d e< s t d i o . h > # i n c l u d e< s t r i n g . h > . . . s t a t i cc o n s tc h a r* c o l o r s [ ]={ " R e d " , " O r a n g e " , " Y e l l o w " , " G r e e n " , " B l u e " , " P u r p l e "} ; s t a t i cc o n s tc h a r* w i d t h s [ ]={ " T h i n " , " M e d i u m " , " T h i c k " , " B o l d "} ; . . . c h a rp e n T e x t [ 2 0 ] ; . . . i n tp e n C o l o r=3 ,p e n T h i c k n e s s=2 ; s t r c p y ( p e n T e x t ,c o l o r s [ p e n C o l o r ] ) ; s t r c a t ( p e n T e x t ,w i d t h s [ p e n T h i c k n e s s ] ) ; p r i n t f ( " M yp e ni s% s \ n " ,p e n T e x t ) ;/ /p r i n t s' M yp e ni sG r e e n T h i c k '
The s t r c h r function
c h a r* s t r c h r ( c o n s tc h a r* s ,i n tc ) ;
The s t r c h r ( ) functionshalllocatethefirstoccurrenceof c (convertedtoa c h a r )inthestringpointedtoby s .[Link],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
[Link]/wiki/C_Programming/Print_version
95/118
10/24/13
c h a r a c t e rw ew e r el o o k i n gf o r . * / w h i l e( * s! =' \ 0 '& &* s! =( c h a r ) c ) s + + ; r e t u r n(( * s= =c )?( c h a r* )s:N U L L) ; }
The s t r c m p function
i n ts t r c m p ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ) ;
Arudimentaryformofstringcomparisonisdonewiththestrcmp()[Link],avaluegreaterthanzeroifthefirstislexographically greaterthanthesecond,[Link](ascii)valueofthechararacters,characterbycharacter. [Link]() 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 )[Link], s t r c m p ( ) shallreturnanintegergreaterthan,equalto,orlessthan0,ifthestringpointedtoby s 1 isgreaterthan,equalto,orlessthanthestringpointedtoby s 2 ,respectively. Sincecomparingpointersbythemselvesisnotpracticallyusefulunlessoneiscomparingpointerswithinthesamearray,thisfunctionlexicallycomparesthestringsthattwopointerspointto. Thisfunctionisusefulincomparisons,e.g.
i f( s t r c m p ( s ," w h a t e v e r " )= =0 )/ *d os o m e t h i n g* / ;
The s t r c p y function
c h a r* s t r c p y ( c h a r* r e s t r i c ts 1 ,c o n s tc h a r* r e s t r i c ts 2 ) ;
Somepeoplerecommendalwaysusing s t r n c p y ( ) insteadofstrcpy,toavoidbufferoverflow. The s t r c p y ( ) functionshallcopytheCstringpointedtoby s 2 (includingtheterminatingnullbyte)intothearraypointedtoby s 1 .Ifcopyingtakesplacebetweenobjectsthatoverlap,[Link] 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 ) ;
[Link]/wiki/C_Programming/Print_version
96/118
10/24/13
Thefollowingisapublicdomainimplementationof s t r c p y :
# i n c l u d e< s t r i n g . h > / *s t r c p y* / c h a r* ( s t r c p y ) ( c h a r* r e s t r i c ts 1 ,c o n s tc h a r* r e s t r i c ts 2 ) { c h a r* d s t=s 1 ; c o n s tc h a r* s r c=s 2 ; / *D ot h ec o p y i n gi nal o o p . * / w h i l e( ( * d s t + +=* s r c + + )! =' \ 0 ' ) ; / *T h eb o d yo ft h i sl o o pi sl e f te m p t y .* / / *R e t u r nt h ed e s t i n a t i o ns t r i n g . * / r e t u r ns 1 ; }
The s t r l e n function
s i z e _ ts t r l e n ( c o n s tc h a r* s ) ;
The s t r n c a t function
c h a r* s t r n c a t ( c h a r* r e s t r i c ts 1 ,c o n s tc h a r* r e s t r i c ts 2 ,s i z e _ tn ) ;
The s t r n c m p function
i n ts t r n c m p ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ,s i z e _ tn ) ;
The s t r n c m p ( ) functionshallcomparenotmorethan n bytes(bytesthatfollowanullbytearenotcompared)fromthearraypointedtoby s 1 tothearraypointedtoby s 2 .Thesignofanonzeroreturnvalueisdeterminedbythesignofthedifferencebetween thevaluesofthefirstpairofbytes(bothinterpretedastype u n s i g n e dc h a r )[Link] s t r c m p foranexplanationofthereturnvalue. Thisfunctionisusefulincomparisons,asthe s t r c m p functionis. Thefollowingisapublicdomainimplementationof s t r n c m p :
[Link]/wiki/C_Programming/Print_version
97/118
10/24/13
# i n c l u d e< s t r i n g . h > / *s t r n c m p* / i n t( s t r n c m p ) ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ,s i z e _ tn ) { u n s i g n e dc h a ru c 1 ,u c 2 ; / *N o t h i n gt oc o m p a r e ? R e t u r nz e r o . * / i f( n= =0 ) r e t u r n0 ; / *L o o p ,c o m p a r i n gb y t e s . * / w h i l e( n ->0& &* s 1= =* s 2 ){ / *I fw e ' v er u no u to fb y t e so rh i tan u l l ,r e t u r nz e r o s i n c ew ea l r e a d yk n o w* s 1= =* s 2 . * / i f( n= =0| |* s 1= =' \ 0 ' ) r e t u r n0 ; s 1 + + ; s 2 + + ; } u c 1=( * ( u n s i g n e dc h a r* )s 1 ) ; u c 2=( * ( u n s i g n e dc h a r* )s 2 ) ; r e t u r n( ( u c 1<u c 2 )?1:( u c 1>u c 2 ) ) ; }
The s t r n c p y function
c h a r* s t r n c p y ( c h a r* r e s t r i c ts 1 ,c o n s tc h a r* r e s t r i c ts 2 ,s i z e _ tn ) ;
The s t r n c p y ( ) functionshallcopynotmorethan n bytes(bytesthatfollowanullbytearenotcopied)fromthearraypointedtoby s 2 tothearraypointedtoby s 1 .Ifcopyingtakesplacebetweenobjectsthatoverlap,[Link] 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 .[Link] 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 + + ;
[Link]/wiki/C_Programming/Print_version
98/118
10/24/13
} r e t u r n( c h a r* )l a s t ; }
Thelesscommonlyusedstringfunctions
Thelessusedfunctionsare:
m e m c h r Findabyteinmemory m e m c m p Comparebytesinmemory m e m c p y Copybytesinmemory m e m m o v e Copybytesinmemorywithoverlappingareas m e m s e t Setbytesinmemory s t r c o l l Comparebytesaccordingtoalocalespecificcollatingsequence s t r c s p n Getthelengthofacomplementarysubstring s t r e r r o r Geterrormessage s t r p b r k Scanastringforabyte s t r s p n Getthelengthofasubstring s t r s t r Findasubstring s t r t o k Splitastringintotokens s t r x f r m Transformstring
Copyingfunctions
Them e m c p y function
v o i d* m e m c p y ( v o i d*r e s t r i c ts 1 ,c o n s tv o i d*r e s t r i c ts 2 ,s i z e _ tn ) ;
Them e m m o v e function
v o i d* m e m m o v e ( v o i d* s 1 ,c o n s tv o i d* s 2 ,s i z e _ tn ) ;
The m e m m o v e ( ) functionshallcopy n bytesfromtheobjectpointedtoby s 2 intotheobjectpointedtoby s 1 .Copyingtakesplaceasifthe n bytesfromtheobjectpointedtoby s 2 arefirstcopiedintoatemporaryarrayof n bytesthatdoesnotoverlaptheobjects pointedtoby s 1 and s 2 ,andthenthe n bytesfromthetemporaryarrayarecopiedintotheobjectpointedtoby s 1 .Thefunctionreturnsthevalueof s 1 . Theeasywaytoimplementthiswithoutusingatemporaryarrayistocheckforaconditionthatwouldpreventanascendingcopy,andiffound,doadescendingcopy. Thefollowingisapublicdomain,thoughnotcompletelyportable,implementationof m e m m o v e :
# i n c l u d e< s t r i n g . h > / *m e m m o v e* / v o i d* ( m e m m o v e ) ( v o i d* s 1 ,c o n s tv o i d* s 2 ,s i z e _ tn ) { / *n o t e :t h e s ed o n ' th a v et op o i n tt ou n s i g n e dc h a r s* / c h a r* p 1=s 1 ; c o n s tc h a r* p 2=s 2 ; / *t e s tf o ro v e r l a pt h a tp r e v e n t sa na s c e n d i n gc o p y* / i f( p 2<p 1& &p 1<p 2+n ){ / *d oad e s c e n d i n gc o p y* / p 2+ =n ; p 1+ =n ;
[Link]/wiki/C_Programming/Print_version
99/118
10/24/13
w h i l e( n -! =0 ) * p 1=* p 2 ; }e l s e w h i l e( n -! =0 ) * p 1 + +=* p 2 + + ; r e t u r ns 1 ; }
Comparisonfunctions
Them e m c m p function
i n tm e m c m p ( c o n s tv o i d* s 1 ,c o n s tv o i d* s 2 ,s i z e _ tn ) ;
The m e m c m p ( ) functionshallcomparethefirst n bytes(eachinterpretedas u n s i g n e dc h a r )oftheobjectpointedtoby s 1 tothefirst n bytesoftheobjectpointedtoby s 2 .Thesignofanonzeroreturnvalueshallbedeterminedbythesignofthedifference betweenthevaluesofthefirstpairofbytes(bothinterpretedastype u n s i g n e dc h a r )thatdifferintheobjectsbeingcompared. Thefollowingisapublicdomainimplementationof m e m c m p :
# i n c l u d e< s t r i n g . h > / *m e m c m p* / i n t( m e m c m p ) ( c o n s tv o i d* s 1 ,c o n s tv o i d* s 2 ,s i z e _ tn ) { c o n s tu n s i g n e dc h a r* u s 1=( c o n s tu n s i g n e dc h a r* )s 1 ; c o n s tu n s i g n e dc h a r* u s 2=( c o n s tu n s i g n e dc h a r* )s 2 ; w h i l e( n -! =0 ){ i f( * u s 1! =* u s 2 ) r e t u r n( * u s 1<* u s 2 )?1:+ 1 ; u s 1 + + ; u s 2 + + ; } r e t u r n0 ; }
TheANSICStandardspecifiestwolocalespecificcomparisonfunctions. The s t r c o l l functioncomparesthestringpointedtoby s 1 tothestringpointedtoby s 2 ,bothinterpretedasappropriatetothe L C _ C O L L A T E [Link] 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 [Link] n charactersareplacedintotheresultingarraypointedtoby s 1 ,[Link] n iszero, s 1 ispermitted [Link],[Link]. 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 ; }
[Link]/wiki/C_Programming/Print_version
100/118
10/24/13
Thes t r c s p n ,s t r p b r k ,ands t r s p n functions
s i z e _ ts t r c s p n ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ) ; c h a r* s t r p b r k ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ) ; s i z e _ ts t r s p n ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ) ;
The s t r c s p n functioncomputesthelengthofthemaximuminitialsegmentofthestringpointedtoby s 1 whichconsistsentirelyofcharacters notfromthestringpointedtoby s 2 . The s t r p b r k functionlocatesthefirstoccurrenceinthestringpointedtoby s 1 ofanycharacterfromthestringpointedtoby s 2 ,returningapointertothatcharacteroranullpointerifnotfound. The s t r s p n functioncomputesthelengthofthemaximuminitialsegmentofthestringpointedtoby s 1 whichconsistsentirelyofcharactersfromthestringpointedtoby s 2 . Allofthesefunctionsaresimilarexceptinthetestandthereturnvalue. Thefollowingarepublicdomainimplementationsof s t r c s p n , s t r p b r k ,and s t r s p n :
# i n c l u d e< s t r i n g . h > / *s t r c s p n* / s i z e _ t( s t r c s p n ) ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ) { c o n s tc h a r* s c 1 ; f o r( s c 1=s 1 ;* s c 1! =' \ 0 ' ;s c 1 + + ) i f( s t r c h r ( s 2 ,* s c 1 )! =N U L L ) r e t u r n( s c 1-s 1 ) ; r e t u r ns c 1-s 1 ; / *t e r m i n a t i n gn u l l sm a t c h* / } # i n c l u d e< s t r i n g . h > / *s t r p b r k* / c h a r* ( s t r p b r k ) ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ) { c o n s tc h a r* s c 1 ; f o r( s c 1=s 1 ;* s c 1! =' \ 0 ' ;s c 1 + + ) i f( s t r c h r ( s 2 ,* s c 1 )! =N U L L ) r e t u r n( c h a r* ) s c 1 ; r e t u r nN U L L ; / *t e r m i n a t i n gn u l l sm a t c h* / } # i n c l u d e< s t r i n g . h > / *s t r s p n* / s i z e _ t( s t r s p n ) ( c o n s tc h a r* s 1 ,c o n s tc h a r* s 2 ) { c o n s tc h a r* s c 1 ; f o r( s c 1=s 1 ;* s c 1! =' \ 0 ' ;s c 1 + + ) i f( s t r c h r ( s 2 ,* s c 1 )= =N U L L ) r e t u r n( s c 1-s 1 ) ; r e t u r ns c 1-s 1 ; / *t e r m i n a t i n gn u l l sd o n ' tm a t c h* / }
Thes t r s t r function
c h a r* s t r s t r ( c o n s tc h a r* h a y s t a c k ,c o n s tc h a r* n e e d l e ) ;
Thes t r t o k function
[Link]/wiki/C_Programming/Print_version
101/118
10/24/13
c h a r* s t r t o k ( c h a r* r e s t r i c ts 1 ,c o n s tc h a r* r e s t r i c td e l i m i t e r s ) ;
Asequenceofcallsto s t r t o k ( ) breaksthestringpointedtoby s 1 intoasequenceoftokens,eachofwhichisdelimitedbyabytefromthestringpointedtoby d e l i m i t e r s .Thefirstcallinthesequencehas s 1 asitsfirstargument,andisfollowedbycallswitha [Link] 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 [Link],itisthestartofthefirsttoken. The s t r t o k ( ) functionthensearchesfromthereforabyte(ormultiple,consecutivebytes)[Link],thecurrenttokenextendstotheendofthestringpointedtoby s 1 ,andsubsequentsearches [Link],itisoverwrittenbyanullbyte,[Link] s t r t o k ( ) functionsavesapointertothefollowingbyte,fromwhichthenextsearchforatokenshallstart. Eachsubsequentcall,withanullpointerasthevalueofthefirstargument,startssearchingfromthesavedpointerandbehavesasdescribedabove. The s t r t o k ( ) [Link]. Becausethe s t r t o k ( ) functionmustsavestatebetweencalls,andyoucouldnothavetwotokenizersgoingatthesametime,theSingleUnixStandarddefinedasimilarfunction, s t r t o k _ r ( ) ,[Link]:
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 [Link] 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 ,[Link] d e l i m i t e r s maybedifferentfrom [Link] 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 ) ;
[Link]/wiki/C_Programming/Print_version
102/118
10/24/13
Thes t r e r r o r function
c h a r* s t r e r r o r ( i n te r r o r c o d e ) ;
Thisfunctionstoresthemessagein b u f ,whichhasalengthofsize b u f l e n .
Examples
Todeterminethenumberofcharactersinastring,the s t r l e n ( ) functionisused:
# i n c l u d e< s t d i o . h > # i n c l u d e< s t r i n g . h > . . . i n tl e n g t h ,l e n g t h 2 ; c h a r* t u r k e y ; s t a t i cc h a r* f l o w e r =" b e g o n i a " ; s t a t i cc h a r* g e m s t o n e = " r u b y" ; l e n g t h=s t r l e n ( f l o w e r ) ; p r i n t f ( " L e n g t h=% d \ n " ,l e n g t h ) ;/ /p r i n t s' L e n g t h=7 ' l e n g t h 2=s t r l e n ( g e m s t o n e ) ; t u r k e y=m a l l o c (l e n g t h+l e n g t h 2+1 ) ; i f( t u r k e y ){ s t r c p y (t u r k e y ,g e m s t o n e ) ; s t r c a t (t u r k e y ,f l o w e r ) ; p r i n t f (" % s \ n " ,t u r k e y ) ;/ /p r i n t s' r u b yb e g o n i a ' f r e e (t u r k e y) ; }
Notethattheamountofmemoryallocatedfor'turkey'[Link],whichisnotcountedinthelengthsofthestrings.
Exercises
1. [Link]? 2. Whatfunctionsarepossiblymissingfromthelibraryasitstandsnow?
Furtherreading
ALittleCPrimer/CStringFunctionLibrary C++Programming/Code/IO/Streams/string Becausesomanyfunctionsinthestandard s t r i n g . h libraryarevulnerabletobufferoverflowerrors,somepeople([Link] s t r i n g . h libraryand"Cstylestrings"andinsteadusingadynamicstringAPI, suchastheoneslistedintheStringlibrarycomparison([Link] There'satinypublicdomainconcat()function,whichwillallocatememoryandsafelyconcatenateanynumberofstringsinportableC/C++code([Link]
Complextypes
[Link] CcomplextypesallowusgreaterflexibilityinmanagingdatainourCprogram.
Datastructures
Adatastructure("struct")[Link](calleda"member")canbeaccessedbythenameofthevariable,followedbya'.',thenthenameofthemember.(Anotherwaytoaccessamemberisusingthemember operator'>').Themembervariablesofastructcanbeofanydatatypeandcanevenbeanarrayorapointer.
Pointers
Pointersarevariablesthatdon'[Link],
i n t* p o i n t e r=& v a r i a b l e ;
[Link]/wiki/C_Programming/Print_version
103/118
10/24/13
Thistellsusthatthepointerisn'tcurrentlypointingtoanyreallocation. Additionally,todereference(accessthethingbeingpointedat)thepointer,usetheform:
v a l u e=* p o i n t e r ;
Structs
[Link] s t r u c t [Link],
s t r u c tm y s t r u c t { i n ti n t _ m e m b e r ; d o u b l ed o u b l e _ m e m b e r ; c h a rs t r i n g _ m e m b e r [ 2 5 ] ; }v a r i a b l e ;
v a r i a b l e isaninstanceof m y s t r u c t .Youcanomititfromtheendofthe s t r u c t declarationanddeclareitlaterusing:
s t r u c tm y s t r u c tv a r i a b l e ;
Unions
[Link],themembersoccupydifferentareasofmemory,butinaunion,[Link],inthefollowingtype,for example:
u n i o n{ i n ti ; d o u b l ed ; }u ;
[Link]/wiki/C_Programming/Print_version
104/118
10/24/13
Thesizeofaunionisthesizeofitslargestmember.
Typemodifiers
For"register","volatile","auto"and"extern",seeCProgramming/Variables#Other_Modifiers.
NetworkinginUNIX
NetworkprogrammingunderUNIXisrelativelysimpleinC. ThisguideassumesyoualreadyhaveagoodgeneralideaaboutC,UNIXandnetworks.
Asimpleclient
Tostartwith,we'lllookatoneofthesimplestthingsyoucando:initializeastreamconnectionandreceiveamessagefromaremoteserver.
# i n c l u d e< s t d i o . h > # i n c l u d e< s t d l i b . h > # i n c l u d e< s t r i n g . h > # i n c l u d e< u n i s t d . h > # i n c l u d e< a r p a / i n e t . h > # i n c l u d e< s y s / t y p e s . h > # i n c l u d e< n e t i n e t / i n . h > # i n c l u d e< s y s / s o c k e t . h > # d e f i n eM A X R C V L E N5 0 0 # d e f i n eP O R T N U M2 3 4 3 i n tm a i n ( i n ta r g c ,c h a r* a r g v [ ] ) { c h a rb u f f e r [ M A X R C V L E N+1 ] ;/ *+ 1s ow ec a na d dn u l lt e r m i n a t o r* / i n tl e n ,m y s o c k e t ; s t r u c ts o c k a d d r _ i nd e s t ; m y s o c k e t=s o c k e t ( A F _ I N E T ,S O C K _ S T R E A M ,0 ) ; m e m s e t ( & d e s t ,0 ,s i z e o f ( d e s t ) ) ; / *z e r ot h es t r u c t* / d e s t . s i n _ f a m i l y=A F _ I N E T ; d e s t . s i n _ a d d r . s _ a d d r=i n e t _ a d d r ( " 1 2 7 . 0 . 0 . 1 " ) ;/ *s e td e s t i n a t i o nI Pn u m b e r* / d e s t . s i n _ p o r t=h t o n s ( P O R T N U M ) ; / *s e td e s t i n a t i o np o r tn u m b e r* / c o n n e c t ( m y s o c k e t ,( s t r u c ts o c k a d d r* ) & d e s t ,s i z e o f ( s t r u c ts o c k a d d r ) ) ; l e n=r e c v ( m y s o c k e t ,b u f f e r ,M A X R C V L E N ,0 ) ; / *W eh a v et on u l lt e r m i n a t et h er e c e i v e dd a t ao u r s e l v e s* / b u f f e r [ l e n ]=' \ 0 ' ; p r i n t f ( " R e c e i v e d% s( % db y t e s ) . \ n " ,b u f f e r ,l e n ) ; c l o s e ( m y s o c k e t ) ; r e t u r nE X I T _ S U C C E S S ; }
The s o c k e t ( ) functiontellsourOSthatwewantafiledescriptorforasocketwhichwecanuseforanetworkstreamconnectionwhattheparametersmeanismostlyirrelevantfornow.
m e m s e t ( & d e s t ,0 ,s i z e o f ( d e s t ) ) ; / *z e r ot h es t r u c t* / d e s t . s i n _ f a m i l y=A F _ I N E T ; d e s t . s i n _ a d d r . s _ a d d r=i n e t _ a d d r ( " 1 2 7 . 0 . 0 . 1 " ) ;/ *s e td e s t i n a t i o nI Pn u m b e r* / d e s t . s i n _ p o r t=h t o n s ( P O R T N U M ) ; / *s e td e s t i n a t i o np o r tn u m b e r* /
[Link]/wiki/C_Programming/Print_version
105/118
10/24/13
[Link] 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. [Link] h t o n s ( ) [Link] d e s t . s i n _ p o r t=2 1 would [Link],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 [Link] r e c v ( ) .Itisimportanttonotethatthedatareceivedwillnotautomaticallybenullterminatedwhen storedinthebuffer,soweneedtodoitourselveswith b u f f e r [ i n p u t l e n ]=' \ 0 ' . Andthat'saboutit! [Link]'[Link] 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 ( ) [Link] s e n d ( ) ,forvariousreasons,maynotbeabletosendallof thebytes,[Link].
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,[Link] 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 ( ) [Link] l i s t e n ( ) [Link] [Link] a c c e p t ( ) [Link] a c c e p t ( ) [Link] "session"socket,[Link](m y s o c k e t )continuestolistenonthespecifiedportforfurtherconnections.
[Link]/wiki/C_Programming/Print_version
106/118
10/24/13
Usefulnetworkfunctions
i n tg e t h o s t n a m e ( c h a r* h o s t n a m e ,s i z e _ ts i z e ) ;
[Link],itfindsthehostnameandstoresitinthearray.Onfailureitreturns1.
s t r u c th o s t e n t* g e t h o s t b y n a m e ( c o n s tc h a r* n a m e ) ;
FAQs
Whataboutstatelessconnections?
Ifyoudon'twanttoexploitthepropertiesofTCPinyourprogramandwouldratherjustuseaUDPconnection,thenyoucanjustreplace S O C K _ S T R E A M with S O C K _ D G R A M inyourcallto s o c k e t ( ) [Link] 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,[Link] [Link],andsomearecontroversial,eachoftheseenjoyswideuse.
Dynamicmultidimensionalarrays
Althoughonedimensionalarraysareeasytocreatedynamicallyusingmalloc,andfixedsizemultidimensionalarraysareeasytocreateusingthebuiltinlanguagefeature,[Link] tocreatethem,[Link]: Theycanbeallocatedasasingleblockofmemory,[Link] rectangular([Link]).Thedisadvantageisthatthesyntaxof [Link],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([Link]).However,italsousesmorespaceandrequires morelevelsofindirectiontoindexinto,[Link],eachofwhichcanbeexpensive. Formoreinformation,[Link],question6.16([Link] Insomecases,[Link],acommontechniquewastodefineamultidimensionalarray,whereeachcolumncontaineddifferent [Link],columnsofatwodimensionalcharacterarraymightcontainlastname,firstname,address,etc. Incaseslikethis,itisbettertodefineastructurethatcontainstheinformationthatwasstoredinthecolumns,[Link],such [Link],itisbettertocreateastructureforthealbumthatcontainsinformationaboutthealbum,[Link] usedtostorethecollection. [Link],a2dimensionalarraywithsizesxandyhasx*yelements,thereforecanbecreatedby
i n td y n a m i c _ m u l t i _ a r r a y [ x * y ] ;
[Link]/wiki/C_Programming/Print_version
107/118
10/24/13
Theindexisslightlytrickierthanbefore,butcanstillbeobtainedbyy*i+[Link]
s t a t i c _ m u l t i _ a r r a y [ i ] [ j ] ; d y n a m i c _ m u l t i _ a r r a y [ y * i + j ] ;
Somemoreexampleswithhigherdimensions:
i n td i m 1 [ w ] ; i n td i m 2 [ w * x ] ; i n td i m 3 [ w * x * y ] ; i n td i m 4 [ w * x * y * z ] ; d i m 1 [ i ] d i m 2 [ w * j + i ] ; d i m 3 [ w * ( x * i + j ) + k ]/ /i n d e xi sk+w * j+w * x * i d i m 4 [ w * ( x * ( y * i + j ) + k ) + l ]/ /i n d e xi sw * x * y * i+w * x * j+w * k+l
Constructorsanddestructors
Inmostobjectorientedlanguages,[Link],[Link] [Link],calledattheendofanobject'slifetime,areimportantinsystemswhereanobjectholdsexclusiveaccesstosomeresource,anditisdesirableto ensurethatitreleasestheseresourcesforusebyotherobjects. SinceCisnotanobjectorientedlanguage,[Link],thisleadstoapotentialforerrors,sinceoperationson [Link],possiblytakinginitializationparameters,asinthisexample:
s t r u c ts t r i n g{ s i z e _ ts i z e ; c h a r* d a t a ; } ;
Similarly,ifitislefttotheclienttodestroyobjectscorrectly,theymayfailtodoso,[Link],suchasthisone:
v o i df r e e _ s t r i n g ( s t r u c ts t r i n g* s ){ a s s e r t( s! =N U L L ) ; f r e e ( s > d a t a ) ; / *f r e em e m o r yh e l db yt h es t r u c t u r e* / f r e e ( s ) ; / *f r e et h es t r u c t u r ei t s e l f* / }
Nullingfreedpointers
Asdiscussedearlier,after f r e e ( ) hasbeencalledonapointer,[Link],mostmodernplatformscannotdetectwhensuchapointerisusedbeforebeingreassigned. Onesimplesolutiontothisistoensurethatanypointerissettoanullpointerimmediatelyafterbeingfreed: [18]
[Link]/wiki/C_Programming/Print_version
108/118
10/24/13
f r e e ( p ) ; p=N U L L ;
Unlikedanglingpointers,[Link],programscanincludeerrorchecksforthenullvalue,[Link] locations,amacrocanbeused:
# d e f i n eF R E E ( p ) d o{f r e e ( p ) ;( p )=N U L L ;}w h i l e ( 0 )
Unfortunately,[Link],someCexpertsregardthisidiomasdangerousduetocreatingafalsesenseofsecurity.
Macroconventions
BecausepreprocessormacrosinCworkusingsimpletokenreplacement,theyarepronetoanumberofconfusingerrors,someofwhichcanbeavoidedbyfollowingasimplesetofconventions: 1. [Link],iftheyareexpressions,[Link]: 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. [Link],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,[Link] s q u a r e( x + + ) ,afterthemacroinvocationwillxbeincrementedby2 3. Ifamacroproducesmultiplestatements,ordeclaresvariables,itcanbewrappedina do{...} while(0)loop,[Link],suchasthebodyofanif statement,[Link]'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"[Link]."[1]([Link] ([Link] tabs,makesureyoukeepitconsistentwithprojectsyouareworkingon,becausemixingtabsandspacescancausecodetobecomeunreadable. 2. [5]([Link] 3. [[Link] 4. "CodingConventionsforC++andJava"([Link] Thisdeliberatechoicewasmadebecausealigningthoseprettystarsisalargewasteoftimeanddiscouragesthemaintenanceofinlinecomments.", 5. wiki:BigBlocksOfAsterisks,"Codecraft"([Link] 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"([Link] ThereareahugenumberofCstyleguidelines. "CandC++StyleGuides"([Link] TheMotorIndustrySoftwareReliabilityAssociation(MISRA)publishes"MISRAC:GuidelinesfortheuseoftheClanguageincriticalsystems".(Wikipedia:MISRAC[7]([Link]
Candbeyond Languageextensions
MostCcompilershaveoneormore"extensions"tothestandardClanguage,todothingsthatareinconvenienttodoinstandard,portableC.
[Link]/wiki/C_Programming/Print_version
109/118
10/24/13
Someexamplesoflanguageextensions: inlineassemblylanguage interruptserviceroutines
Externallinks
GNUC:ExtensionstotheCLanguage([Link] C/C++interpreterChextensionstotheClanguageforscripting([Link] SDCC:StorageClassLanguageExtensions([Link] 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. GCC:"Optimizecommonrotateconstructs"([Link] "CleanupsinROTL/ROTRDAGcombinercode"([Link] "replaceprivatecopyofbitrotationroutines"([Link] CFAQ([Link] UnderstandingC++/CPreprocessor DavidHart,JonReid."9CodeSmellsofPreprocessorUse"([Link] HPCCompilerReferenceManual([Link] C++reference:Predefinedpreprocessorvariables([Link] "CompileTimeAssertionsinC"([Link] Wikipedia:C++0x#Staticassertions Wirzenius,[Link]([Link] Meyers,Randy(May2001)."TheNewC:XMacros". [Link]'sJournal.[Link] Beal,Stephan(August2004). Supermacros.[Link] KeithSchwarz."AdvancedPreprocessorTechniques"([Link] Wirzenius,[Link]([Link] C996.2.5/15 "Bug478901...libpng1.2.34andearliermightfreeundefinedpointers"([Link] [Link]:"Whyisn'tapointernullaftercallingfree?"([Link] [Link]:Question2.6([Link] 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
[Link]/wiki/C_Programming/Print_version
110/118
10/24/13
Java_Programming/Keywords/native
Perl
TomixPerlandC,[Link](oraClibrary)whichonewishestousewithPerl. [Link]"h2xs"application(e.g."h2xsAnModulename").[Link],[Link] [Link],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"[Link]"and"make". Furtherdetailscanbefoundontheperlxstut([Link]
Python Forfurtherreading
EmbeddedSystems/MixedCandAssemblyProgramming
References
1. 2. 3. 4. Lesson:47fromNeHeProductions([Link] CgBumpmappingbyRazvanSurdulescuatGameDev([Link] [[Link] [Link]
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,[Link].
p u t s( " H it h e r e ! " ) ;
[Link]/wiki/C_Programming/Print_version
111/118
10/24/13
CReferenceTables
ThissectionhassometablesandlistsofCentities.
ReferenceTables
ListofKeywords
ANSIC(C89)/ISOC(C90)keywords:
a u t o b r e a k c a s e c h a r c o n s t c o n t i n u e d e f a u l t d o
d o u b l e e l s e e n u m e x t e r n f l o a t f o r g o t o i f
i n t l o n g r e g i s t e r r e t u r n s h o r t s i g n e d s i z e o f s t a t i c
s t r u c t s w i t c h t y p e d e f u n i o n u n s i g n e d v o i d v o l a t i l e w h i l e
KeywordsaddedtoISOC(C99)(Supportedonlyinnewcompilers):
_ B o o l _ C o m p l e x
_ I m a g i n a r y i n l i n e
r e s t r i c t( h t t p : / / e n . w i k i p e d i a . o r g / w i k i / R e s t r i c t )
ListofStandardHeaders
ANSIC(C89)/ISOC(C90)headers:
Veryoldcompilersmaynotincludesomeorallofthefollowingheaders: HeadersaddedtoISOC(C94/C95)inAmendment1(AMD1):
< i s o 6 4 6 . h >
< w c h a r . h >
< w c t y p e . h >
HeadersaddedtoISOC(C99)(Supportedonlyinnewcompilers):
[Link]/wiki/C_Programming/Print_version
112/118
10/24/13
TableofOperators
Operatorsinthesamerowofthistablehavethesame precedenceandtheorderofevaluationisdecidedbythe associativity(lefttoright or righttoleft ).Operatorsclosertothetopofthistablehave higherprecedencethanthoseinasubsequent group. Operators Description Postfixoperators ExampleUsage Associativity
( ) [ ]
s w a p( x ,y ) a r r[ i ]
Lefttoright
o b j . m e m b e r
>
p t r > m e m b e r
UnaryOperators
! ~
! e o f _ r e a c h e d ~ m a s k n u m
[1] ++ ++ +& * s i z e o f s i z e o f ( ) ( t y p e )
Righttoleft
MultiplicativeOperators
*/%
multiplication,divisionand modulusoperators
Lefttoright
c e l s i u s _ d i f f*9 . 0/5 . 0
AdditiveOperators
+-
Lefttoright
e n d-s t a r t+1
additionandsubtractionoperators
BitwiseShiftOperators Lefttoright
< < > >
leftshiftoperator rightshiftoperator
RelationalInequalityOperators
[Link]/wiki/C_Programming/Print_version
113/118
10/24/13
<>< => =
RelationalEqualityOperators
= =! =
equalto,notequalto
Lefttoright
c h o i c e! =' n '
BitwiseAndOperator
& b i t s&c l e a r _ m a s k _ c o m p l e m e n t
Lefttoright
BitwiseXorOperator
^ b i t s^i n v e r t _ m a s k
Lefttoright
BitwiseOrOperator
| b i t s|s e t _ m a s k
Lefttoright
LogicalAndOperator
& & a r r! =0& &a r r > l e n! =0
Lefttoright
LogicalOrOperator
| |
seeLogicalExpressions ConditionalOperator
Lefttoright
a r r= =0| |a r r > l e n= =0
Righttoleft
? : s i z e! =0?s i z e:0
AssignmentOperators
= + ==* =/ = % =& =| =^ = < < => > =
i=0
Righttoleft
n u m/ =1 0
CommaOperator
, i=0 ,j=i+1 ,k=0
Lefttoright
TableofOperatorsFootnotes
[1]Veryoldcompilersmaynotrecognizetheunary + operator.
TableofDataTypes
Type SizeinBits Comments PrimitiveTypesinANSIC(C89)/ISOC(C90) AlternativeNames
[Link]/wiki/C_Programming/Print_version
114/118
10/24/13
s i g n e dc h a r
sameas c h a r
Charactersstoredlikefortype c h a r . Canstoreintegersintherange127~127portably[1].
u n s i g n e dc h a r
sameas c h a r
Charactersstoredlikefortype c h a r . Canstoreintegersintherange0~255portably.
s h o r t
16,sizeof c h a r
Canstoreintegersintherange32767~32767portably[2]. Usedtoreducememoryusage(althoughtheresultingexecutablemaybelargerandprobablyslowerascomparedtousing i n t .
s h o r ti n t , s i g n e ds h o r t , s i g n e ds h o r t i n t
u n s i g n e ds h o r t
sameas s h o r t
Canstoreintegersintherange0~65535portably. Usedtoreducememoryusage(althoughtheresultingexecutablemaybelargerandprobablyslowerascomparedtousing i n t .
u n s i g n e ds h o r ti n t
i n t
16,sizeof s h o r t
Representsthe"normal"sizeofdatatheprocessordealswith(thewordsize)thisistheintegraldatatypeusednormally. Canstoreintegersintherange32767~32767portably[2].
s i g n e d , s i g n e di n t
u n s i g n e di n t
sameas i n t
Canstoreintegersintherange0~65535portably.
u n s i g n e d
l o n g
32,sizeof i n t
Canstoreintegersintherange2147483647~2147483647portably[3].
l o n gi n t , s i g n e dl o n g , s i g n e dl o n gi n t
u n s i g n e dl o n g
sameas l o n g
Canstoreintegersintherange0~4294967295portably.
u n s i g n e dl o n gi n t
f l o a t
sizeof c h a r
d o u b l e
sizeof f l o a t
l o n gd o u b l e
sizeof d o u b l e
u n s i g n e d cannotbespecified.
[Link]/wiki/C_Programming/Print_version
115/118
10/24/13
PrimitiveTypesaddedtoISOC(C99)
l o n gl o n gi n t , s i g n e dl o n gl o n g , s i g n e d l o n gl o n gi n t
l o n gl o n g
64,sizeof l o n g
Canstoreintegersintherange9223372036854775807~9223372036854775807portably[4].
u n s i g n e dl o n gl o n g
sameas l o n gl o n g
Canstoreintegersintherange0~18446744073709551615portably.
u n s i g n e dl o n gl o n gi n t
i n t m a x _ t
themaximumwidthsupportedby theplatform
Canstoreintegersintherange(1<<n1)+1~(1<<n1)1,with'n'thewidthofintmax_t. Usedbythe"j"lengthmodifierintheCProgramming/FileIO#Formattedoutputfunctions:theprintffamilyoffunctions.
u i n t m a x _ t
sameas i n t m a x _ t
Canstoreintegersintherange0~(1<<n)1,with'n'thewidthofuintmax_t.
UserDefinedTypes
s t r u c t
sumofsizeofeachmember
Saidtobean aggregatetype.
u n i o n
sizeofthelargestmember
Saidtobean aggregatetype.
e n u m
sizeof c h a r
Enumerationsareaseparatetypefrom i n t s,thoughtheyaremutuallyconvertible.
t y p e d e f
sameasthetypebeinggivena name
t y p e d e f hassyntaxsimilartoastorageclasslike s t a t i c , r e g i s t e r or e x t e r n .
DerivedTypes[5]
0 alwaysrepresentsthenullpointer(anaddresswherenodatacanbeplaced),irrespectiveofwhatbitsequencerepresentsthe
t y p e *
sizeof c h a r (pointer)
[ 6 ] t y p e[ i n t e g e r ]
[Link]/wiki/C_Programming/Print_version
116/118
10/24/13
(array)
t y p e( c o m m a d e l i m i t e dl i s to f t y p e s / d e c l a r a t i o n s )
(function)
TableofDataTypesFootnotes
[1]128canbestoredintwo'scomplementmachines([Link]).Veryoldcompilersmaynotrecognizethe s i g n e d keyword. [2]32768canbestoredintwo'scomplementmachines([Link]).Veryoldcompilersmaynotrecognizethe s i g n e d keyword. [3]2147483648canbestoredintwo'scomplementmachines([Link]).Veryoldcompilersmaynotrecognizethe s i g n e d keyword. [4]9223372036854775808canbestoredintwo'scomplementmachines([Link]). [5]Theprecedencesinadeclarationare:
[ ] , ( ) (leftassociative)Highest * (rightassociative)Lowest
[6]ThestandardsdoNOTplaceanyrestrictiononthesize/typeoftheinteger,it'[Link]
allocated,andassuchthelimitonintegerwillbesize_of_max_block/sizeof(type).
Compilers
Free(orwithafreeversion)
Ch_interpreter([Link] lccwin32([Link] GNUCompilerCollection([Link] MinGW([Link] OpenWatcom([Link] 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([Link] SmallDeviceCCompiler(SDCC) targetplatforms:Intel8051compatiblesFreescale(Motorola)HC08MicrochipPIC16andPIC18. [Link]:FPGAhardwareviaXNForVHDLfiles. InteractiveC([Link] targetplatform:HandyBoard(Freescale68HC11)LegoRCX Ccompilersformanydigitalsignalprocessors(DSPs),manyofthemfree,[Link]([Link]
Commercial
IntelCCompiler([Link] MicrosoftVisualC++([Link] ImpulseCTargetplatform:FPGAhardwareviaHardwareDescriptionLanguage(HDL)files. Retrievedfrom"[Link]
[Link]/wiki/C_Programming/Print_version
117/118
10/24/13
Thispagewaslastmodifiedon9June2012,at08:12.
TextisavailableundertheCreativeCommonsAttribution/[Link],youagreetotheTermsofUseandPrivacyPolicy.
[Link]/wiki/C_Programming/Print_version
118/118