•
•
•
•
•
•
•
•
Learn C
on the
Mac
For OS X and iOS
David Mark
|
James Bucanek
ContentsataGlance
AbouttheAuthors ...xiii
AbouttheTechnicalReviewer...xiv
Acknowledgments...xv
Introduction...xvi
Chapter1:GoGettheTools!... 1
Chapter2:ProgrammingBasics ... 11
Chapter3:CBasics:StatementsandFunctions ... 21
Chapter4:CBasics:VariablesandOperators ... 43
Chapter5:Debugging... 75
Chapter6:ControllingYourProgram’sFlow ... 93
Chapter7:PointersandParameters... 137
Chapter8:MoreDataTypes... 177
Chapter9:TheCommandLine ... 229
Chapter10:DesigningYourOwnDataStructures ... 291
Chapter11:WorkingWithFiles... 331
Introduction
WelcomeAboard
Welcome!ChancesarethatyouarereadingthisbecauseyoulovetheMac.Andnotonlydoyou lovetheMac,butyoualsolovetheideaoflearninghowtodesignanddevelopyourveryownMac programs.
You’vedefinitelycometotherightplace.
ThisbookassumesthatyouknowhowtouseyourMac.That’sit.Youdon’tneedtoknow anythingaboutprogramming—notonelittlebit.We’llstartoffwiththebasics,andeachstepwe takewillbeasmallonetomakesurethatyouhavenoproblemfollowingalong.
Thisbookwillfocusonthebasicsofprogramming.Atthesametime,you’lllearnthe essentialsoftheCprogramminglanguage.
InDouglasAdam’sbookTheHitchhiker'sGuidetotheGalaxy,theanswerto“theUltimate QuestionofLife,theUniverse,andEverything”isdeterminedtobe“42.”Thatansweris,of course,wrong;thecorrectansweris“C.”
TheClanguageisthewellspringofsoftware.Thenothing-short-of-miraculousrevolutionin computingandconsumerelectronicsoverthepasthalfcenturyhaslargelybeenaccomplished usingC,languagesthataredirectdescendantsofC(Objective-C,C++),orlanguagesdesignedto worklikeC(Java,C#).LearnCandtheprogrammingworldisyouroyster.
“MyfirstcluethatIhadunderestimatedmyaudiencewaswhenIstartedgettinge-mails fromfifthgraderswhoweremakingtheirwaythroughthebook.Fifthgraders!Andnotjustone butlotsofnine-,ten-,andeleven-year-oldkidsweredigginginandlearningtoprogram.Cool! Andthebestpartofallwaswhenthesekidsstartedsendingmeactualshippingproductsthat theycreated.Youcan’timaginehowproudIwasandstillam.”
Davewasreallyontosomething.Overtheyears,we’veheardfromsoccermoms,hobbyists, evenfolkswhowereusingtheMacfortheveryfirsttime,allofwhommadetheirwaythrough
LearnContheMacandcameouttheotherend,proud,strong,andfullofknowledge. Sowhatdoyouneedtoknowtogetstarted?AlthoughlearningCbyjustreadingabookis possible,you’llgetthemostoutofthisbookifyouruneachexampleprogramasyouencounter it.Todothis,you’llneedaMacrunningOSX(preferablyversion10.6.8orlater)andanInternet connection.You’llneedtheInternetconnectiontodownloadthefreetoolsApplehasgraciously providedforanyoneinterestedinprogrammingtheMacandtodownloadtheprojectsthatgo alongwiththisbook.
Again,ifyouknownothingaboutprogramming,don’tworry.Thefirstfewchaptersofthis bookwillbringyouuptospeed.Ifyouhavesomeprogrammingexperience(orevenalot),you mightwanttoskimthefirstfewchapters,andthendigrightintotheCfundamentalsthatstartin Chapter3.
TheLayoftheLand
Here’saquicktourofwhat’stocomeinthisbook.
Chapter1showsyouhowtogetthefreesoftwaretoolsyou’llusethroughoutthis book.
Chapter2explainssomeofthebasicsofhowcomputerprogramsarebuilt.
Chapter3showsyouhowtoembedaseriesofprogrammingstatementsintoa reusablefunction,somethingyoucancallagainandagain.
Chapter4addsvariablesandoperatorsintothemix,bringingthepowerof mathematicalexpressionsintoyourprograms.
Chapter5teachesyouhowtowatchyourprogramexecute,line-by-line,toseethat it’sdoingtherightthing,orfixitifit’snot.
Chapter9takesabreaktoshowyouhowtodeployyourfinishedprogramanduseit fromthecommandline.
Chapter10divesevendeeperintodataandteachesyouhowtodesignyourown customdatastructures.
Chapter11showsyouhowtosaveyourprogram’sdataandreaditbackinagainby introducingtheconceptofthedatafile.
Chapter12givesyousometechniquesfordealingwitherrors,forwhenthingsgo wrong.
Chapter13coversavarietyofadvancedtopics—typecasting,unions,recursion, sorting,collections,andmuchmore.
Finally,Chapter14wrapsthingsupandpointsyoutothenextsteponyourjourney.
1
Chapter
GoGettheTools!
Ifyouwanttobuildahouse,youneedasolidsetofwell-craftedtools.Building computerprogramsisnodifferent.Programmingrequiresaspecializedsetof developmenttools---basically,programsthatmakeprograms.
IntheearlydaysofC,youonlyneededafew,relativelysimpletools.As computershavebecomemoresophisticated,sohastheuniverseof
developmenttools.Today,it’snotuncommontoemploydozensofprogramsto createevena‘‘simple’’application:editors,compilers,linkers,debuggers, emulators,profilers,analyzers,andmore.Addtothatlistprogramsthathelpyou finddocumentation,crossreferenceyourcode,recordyourdevelopment history,and,well,it’sstartingtolooklikeawholehardwarestorefulloftools! ThegoodnewsisthatApplehascometoyourrescue.JustasApplehasused anelegantuserinterfacetodemystifytheirmostsophisticatedapplications, they’vedonethesameforsoftwaredevelopers.(That’syou!)
Installing Xcode
Apple’sXcodeisacompletehardwarestoreofsoftwaredevelopmenttools, packagedanddeliveredasasingleapplication.Allyouhavetodoiswriteyour programandXcodewill---behindthescenes---directthescoresofindividual developmenttoolsneededtoturnyourideaintoreality.Itwouldmakethe WizardofOzproud.
AndgettingXcodeintoyourcomputercouldn’tbeeasier.TheentireXcode developmentsuiteisavailablefromtheAppStore.
LaunchtheAppStore,gototheDeveloperToolscategory(orjustsearchfor ‘‘Xcode’’),andclicktoinstallXcode,asshowninFigure1-1.Don’tworryifyour screenlooksabitdifferentthanthefigure.AppleisconstantlyupdatingXcode, sotherewillprobablybeanewversionofXcodeintheAppStorebythetime thisbookhitstheshelves(oryourscreen).
Figure1-1.InstallingXcodefromtheAppStore
That’sit!SitbackandwaitforXcodetodownloadandinstall.Andyou’regoing tohavetowaitawhile,asit’sareallybigapplication.Soamuseyourselfwiththe restofthischapterwhileitdownloads.SwitchtothePurchasesview,atthetop oftheAppStorewindow,ifyouwantseehowthedownloadisprogressing.
How much is that IDE in the Window?
Xcodehasgonethroughvariouspricesinthepast.Applereallywantsyouto creategreatapplicationsandhasstrived,forthemostpart,tomakeits developmentstoolsfreelyavailable.
ItusedtobethatXcodewasonlyavailabletoregistereddevelopers.Becoming aregistereddeveloperusuallycostsmoney,soXcodewas‘‘free’’onlyinthe sensethattheprizeinsideacerealboxis‘‘free.’’
NOTE:Ifyou’rerunninganolderversionofOSXanddon’thaveaccesstotheApp Store,youcanstilldownloadanearlierversionofXcode—butwedon’trecommend it.
Thefirstproblemyou’regoingtoencounterishowtogetyourcopyofXcode.Asof thiswriting,youmustbearegistereddevelopertoobtainanolderversionofXcode. Unfortunately,Applenolongeroffersfreedeveloperregistration—largelybecause XcodeisnowavailableforfreeintheAppStore—soyou’llhavetopaytoregister, andthatcanbeexpensive.Ifyouarearegistereddeveloperorhaveaccessto Apple’sUniversityProgramforhighereducation,youcanloginto
http://developer.apple.com/anddownloadthetools.
ButyourbiggestproblemisgoingtobethedifferencesbetweenthecurrentXcode andolderversions.Thecodeexamplesinthisbookwillstillworkandmakesense, butthecommands,windows,features,andcontrolsareallgoingtobesubstantially different.You’regoingtohavetofigureoutalotonyourown.
Wecertainlydon’twanttodiscourageanyonefromlearningContheMac,butwe stronglyrecommendyouupgradetothelatestversionofOSXsoyouhaveaccessto thelatestversionofXcode.
What’s a Registered Developer?
Sowhat’saregistereddeveloperanddoyouneedtobeone?Theshortanswer is‘‘notyet.’’
Becomingaregistereddevelopergrantsyouaccesstoevenmoretoolsand resourcesthanjustXcode.Butyoudon’tneedanyofthattowritegreat
applicationsforOSXoriOS!Youdon’tneedittouseXcode.Youcertainlydon’t needtobearegistereddevelopertoworkthroughthisbook(ormostother books,forthatmatter).
Youwillneedtobecomearegistereddeveloperifyouwanttosell,orevengive away,yourmasterpiecesonanyofApple’sappstores.Howcoolwouldthatbe? Youcanregisteratanytime,sothere’snohurry.Whenyouareready,visit
Getting the Projects
Whileyou’restillwaitingforXcodetodownloadandinstall,whynotgetthe projectfilesforthisbook?Everythingyouneedtocreatetheprojectsinthis bookisdescribedinthetext,butdownloadingthefinishedprojectsfromthe Apresswebsitewillsaveyoualotoftyping.
Gotohttp://www.apress.com/book/view/9781430245339.Belowthebook’s description,you’llseesomefoldertabs,oneofwhichislabeledSource
Code/Downloads.Clickthattab.Nowfindthelinkthatdownloadstheprojectsfor thisbook.ClickthatlinkandafilenamedLearn C Projects.zipwilldownload toyourharddrive.
LocatethefileLearn C Projects.zipinyourDownloadsfolder(orwhereverthe browsersavedit).Double-clickthefiletoextractitscontents,leavingyouwitha foldernamedLearn C Projects.Movethefolderwhereveryoulike.
Using Xcode
Figure1-2.Xcodestartupwindow
Thestartupwindowhasconvenientbuttonsthatcreateanewproject,reopena recentlyvisitedproject,linktotheXcodedocumentation,andsomeotherstuff we’renotgoingtocoverinthisbook.
Xcodeorganizesyourworkaroundaproject.Aprojectisacollectionoffilesthat ultimatelyproduceaprogram.Italwaysconsistsofaprojectdocument(theicon withthelittleblueprint)storedinsideafolder,asshowninFigure1-3.Thatfolder iscalledtheprojectfolder.Youopenaprojectbyopeningtheproject
Figure1-3.ThecontentsofasimpleXcodeprojectfolder
WhenopenedinXcode,yourprojectappearsinaworkspacewindow,asshown inFigure1-4.Thewindowisfullofcrypticsettingsandseeminglycomplex controls,butdon’tworry.Untilyougettosomereallyadvancedprogramming, youwon’tneedtofiddlewithanyofthesesettings.
Figure1-4.AworkspacewindowinXcode
Creating a New Xcode Project
WhileXcodestillhasthat‘‘newcarsmell,’’let’stakeitforaquickspinaround theblockandcreateanewXcodeproject.
presentedwiththenewprojectassistant,showninFigure1-5,whichwillhelp youspecifythetypeofnewprojectyouwanttocreate.
Figure1-5.Newprojectassistant
Theleftsideofthenewprojectassistantletsyouchoosewhethertocreatea projectforiOS(onethatwillrunonyouriPhone,iPad,oriPodtouch)orforMac OSX(onethatwillrunonyourcomputer).SelectApplicationintheMacOSX section.
Next,youneedtodecidethetypeofMacOSXapplicationyouwanttobuild.In thisbook,you’regoingtolearnhowtobuildsimple,text-onlyapplicationsthat displaytextinawindow,onelineatatime.Onceyoufinishthisbook,youcan moveontobooksthatwillteachyouhowtousetheskillsyou’vejustmastered tobuildapplicationsthatwillrunonyouriOSdeviceoronyourMacwiththe graphicalelementsthatdefinethosedevices.
Thenextscreen(Figure1-6)letsyounameyournewprojectandspecifyafew otheroptions.Foracommand-linetooltheoptionsareprettysimple.EnterHello intheNamefield.
ThefieldCompanyIdentifierallowsXcodetospecifywhomadethisapplication. Typically,thisisareverseofadomainnameyou’vesetupforyourproduct. Unlessyou’vegotaspecificidentifieryouwanttouse,useonewe’vesetupfor thisbook.Entercom.apress.learncintheCompanyIdentifierfield.
Figure1-6.Projecttemplateoptions
SettheTypepop-upmenutoC,sinceyou’llbewritingallyourprogramsinthe Cprogramminglanguage.
AutomaticReferenceCountingdoesn’tapplytoC.LeavetheUseAutomatic ReferenceCountingcheckboxunchecked.
Nowthatyouroptionsareallset,clicktheNextbutton.
createamasterfolder,perhapsnamedMyLearnCProjects,inwhichyoucan storealltheprojectsyoucreateforthisbook
The Workspace Window
Xcodeopensyournewprojectinaworkspacewindow,asshowninFigure1-7. Theworkspacewindowisdividedupintopanesorviews.Ontheleftarethe navigators(howyougetaroundyourproject).Inthemiddleareyoureditors (whereyouwriteanddesignyourapplication).Toeditafile,double-clickthefile inthenavigatoranditwillappearintheeditor.Ontherightareutilities
(inspectors,libraries,help,andsuch).Anyoftheseviewscanbehiddenasyou work.InFigure1-7,theutilitiesarehiddenforthesakeofsimplicity.
Figure1-7.Helloprojectworkspacewindow
Running a Project
OnereallynicethingaboutXcodeprojecttemplatesisthattheyalwayscreatea finishedproject.Thatis,everythingitneedstobuildandrunisreadyrightfrom thestart.Ofcourse,itwon’tdoanythinguseful.Infact,itreallywon’tdomuch ofanythingatallbeyondstartingandthenstoppingagain.Changingyour projecttodosomethingusefulisyourjob.
Butdon’tletthatstopyou;let’smakeyournewprojectdonothing!Clickthe Runbutton(thebigPlaybuttonintheupperleftcorneroftheworkspace window).Xcodewillassembleallofthepartsofyourproject(aprocessknowas building)andwillthenexecuteit.
Don’texpectfireworks.TheXcodecommand-linetemplatemakesaprojectthat causesthewords‘‘Hello,World!’’toappearinthelowerrightpane(calledthe console),asshowninFigure1-7.
HELLO,WORLD!
DennisRitchiedevelopedtheoriginalClanguageoveraperiodoftimebetweenhippiesand disco.Yearslater,heworkedwithBrianKernighantopenacompletedescriptionofthe language.ThisversionofCbecameknownasK&RC.
Intheirseminalbook,theveryfirstexampleofC(it’sonpage6;youcanlookitup)wasatiny programthatcausedthewords“Hello,World”toappearonaconsole.Andinthosedaysitwas probablyaTeletypeconsole—awashing-machine–sizedmechanicaltypewriterwithrollpaper. Eversincethatday,practicallyeverybookthatexplains,teaches,ordescribesaprogramming languagestartswithanexamplethatmakesthewords“Hello,World”appearsomewhere.Inthe spiritofthatgrandtradition,wearehonorboundtoteachyouhowtomake“Hello,World!” appearonyourMac!
Moving On
Believeitornot,youarenowreadytolearnContheMac!
You’veinstalledallofthetoolsyouneedtocreateOSXapplications,and you’vecreated,built,andrunabrandnewapplication.That’sprettygoodfor onechapter!
2
Chapter
ProgrammingBasics
BeforewedigintoCprogrammingspecifics,let’sspendafewminutes
discussingthebasicsofprogramming.Whywriteacomputerprogram?Howdo computerprogramswork?We’llanswerthesequestionsandlookatallofthe elementsthatcometogethertocreateacomputerprogram,suchassource code,acompiler,andthecomputeritself.
Ifyouarealreadyfamiliarwiththebasicsofprogramming,pleasefeelfreeto skimthroughthischapterand,ifyoufeelcomfortablewiththematerial,skipon aheadtoChapter3.Thegoalhereistogetyoufamiliarwiththestepsinvolved increatingarunningasimpleprogram.
Programming
Whywriteacomputerprogram?Therearemanyreasons.Someprogramsare writtenindirectresponsetoaproblemtoocomplextosolvebyhand.For example,youmightwriteaprogramtocalculateavalueto5,000decimalplaces ortodeterminetheprecisemomenttofiretheboostersthatwillsafelylandthe MarsRover.
Otherprogramsarewrittenasperformanceaids,allowingyoutoperforma regulartaskmoreefficiently.Youmightwriteaprogramtohelpyoubalance yourcheckbook,keeptrackofyourbaseballcardcollection,orlayoutthis month’sissueofDinosaurToday.
Some Alternatives to C
Asmentionedpreviously,Cisoneofthemostpopularprogramminglanguages around.There’sverylittleyoucan’tdoinC(orinsomevariantofC),onceyou knowhow.Ontheotherhand,aCprogramisnotnecessarilythebestsolution toeveryprogrammingproblem.
Forexample,supposeyouaretryingtobuildadatabasetotrackyour company’sinventory.RatherthanwritingacustomCprogramtosolveyour problem,youmightbeabletouseanoff-the-shelfpackagelikeFileMakerProor perhapsaUnix-basedsolutionlikeMySQLorPostgreSQLtoconstructyour database.Theprogrammerswhocreatedthesepackageshavealreadysolved mostoftheknottydatabase-managementproblemsyou’dfaceifyoutriedto writeyourprogramfromscratch.Thelessonhereisthis:beforeyoutacklea programmingproblem,examineallthealternatives.Youmightfindonethatwill saveyoutimeandmoneyoronethatwillprovetobeabettersolutiontoyour problem.
SomeproblemscanbesolvedusingtheMac’sbuilt-inscriptinglanguage, AppleScript.JustlikeC,AppleScriptisaprogramminglanguage.Typically,you useAppleScripttocontrolotherapplications.Forexample,youcouldcreatean AppleScriptscriptthatgetsyourdailycalendarfromiCal,formatsitjusttheway youlikeitusingTextEdit,andthenprintsouttheresults.Oryoucouldwritea scriptthatlaunchesSafariandopenseachofyourbookmarkednewssitesina separatewindow.Ifyoucanuseexistingapplicationstodowhatyouneed, chancesaregoodyoucanuseAppleScripttogetthejobdone.
Someapplicationsfeaturetheirownproprietaryscriptinglanguage.For instance,MicrosoftExcelletsyouwriteprogramsthatoperateonthecells withinaspreadsheet.Somewordprocessingprogramsletyouwritescriptsthat controljustabouteverywordprocessingfeatureinexistence.Although
proprietaryscriptinglanguagescanbequiteuseful,theyaren’tmuchhelp outsidetheirintendedenvironments.Youwon’tfindmuchusefortheExcel scriptinglanguageoutsideExcel,forexample.
What About Objective-C, C#, C++, and Java?
whenthenextC-basedlanguagehitsthestreets,you’llhavealeguponthat
What’s the Best Programming Language
for the Mac or iOS Devices?
Alltheprogramsinthisbookwillrunintheconsole,asimplescrollingtext you’llwanttodigintoLearnObjective-ContheMac,2nd
asasequeltoLearnObjective-C.InsteadoffocusingonCocoa,though,it focusesonCocoaTouch.
So,first,finishthisbook,andthenmakeyourwaythroughLearnObjective-Con theMac.IfMacapplicationdesignisyourgoal,nextpickupacopyofLearn CocoaontheMac.IftheiPhone,iPodtouch,oriPadisyourthing,pickup BeginningiOSDevelopment.
Andthat’stheroadmap.Oh,onemorething.Youcanfindeachofthesebooks ontheApresswebsiteathttp://www.apress.com.
The Programming Process
InChapter1,youinstalledtheMacdevelopmenttoolsandwentthroughthe processofcreatingaproject,whichyouthenbuiltandran.Let’stakealookat theprogrammingprocessinabitmoredetail.
Source Code
Nomattertheirpurpose,mostcomputerprogramsstartassourcecode.Your sourcecodewillconsistofasequenceofinstructionsthattellsthecomputer whattodo.Sourcecodeiswritteninaspecificprogramminglanguage,suchas C.Eachprogramminglanguagehasitsownsetofrules(calledsyntax)that defineswhatisandisn’tlegalinthatlanguage.
Yourmissioninreadingthisbookistolearnhowtocreateuseful,efficient,and, bestofall,legalCsourcecode.
IfyouwereprogrammingusingeverydayEnglish,yoursourcecodemightlook likethis:
‘‘Hi,Computer!Dome afavor.Takethenumbersfrom1to10,
addthemtogether,andthentellmethesum.’’
Listing2-1.SummingNumbers1through10inC #include <stdio.h>
int main (int argc, const char * argv[]) {
int number, sum; sum = 0;
for ( number=1; number<=10; number++ ) sum += number;
printf("The sum of the numbers from 1 to 10 is %d.\n", sum ); return 0;
}
Ifthisprogramdoesn’tmeananythingtoyou,don’tpanic.Justkeepreading.By thetimeyoufinishthisbook,thiswillallmakeperfectsense.
Incaseyouwerewondering,here’swhatappearedintheconsolewindowwhen weranthisprogram:
The sum of the numbers from 1 to 10 is 55.
Wanttotrythisoutforyourself?InChapter1,youdownloadedtheprojectfiles forthebookfromtheApresswebsite.OpentheLearn C Projectsfolderon yourharddrive.Next,openthefoldernamed02.01 - Sample,anddouble-click thefilenamedSample.xcodeprojtoopentheprojectinXcode.
Figure2-1.TheSampleprojectworkspace
RuntheprogrambyclickingtheRunbuttoninthetoolbar,bychoosingthe ProjectRuncommand,orbytyping⌘R.
Theprogramshouldbuildandthenrun,andthetextweshowedyoupreviously shouldappearintheconsolepane.Ifyoudon’tseetheconsolepane,choose theViewDebugAreaShowDebugAreacommand.
OK,enoughreveling.Let’sgetbacktotheprogrammingprocess.
Compiling Your Source Code
NOTE:Don’tlettheterminologybogyoudown.Readtherestofthischapter,justto getabasicsenseoftheprogrammingprocess,andthenmoveontoChapter3.We’ll layouteverythingstep-by-stepforyou,soyouwon’tgetlost.
Thinkoftheprocessofbuildingandrunningyourprogramasathree-stage process.First,Xcodecompilesallyoursourcecodeintoobjectcode.Next,all theobjectcodeinyourprojectislinkedtogetherbyaprogramcalledalinkerto formyourapplication.Thatfinishedapplication(calledanexecutable)iswhat actuallyrunsonyourcomputer.
TakealookatFigure2-2.Thisprojectcontainstwosourcecodefiles,one namedmain.candanothernamedextras.c,aswellasanobjectfilenamed
libc.dylib.Sometimes,you’llfindyourselfmakinguseofsomecodethat othershavealreadycompiled.Perhapstheywanttosharetheircodebutdonot wanttoshowyoutheirsourcecode.ThisisthewayApplemakestheircode availabletoprogrammers.Theycompilethecodeandsaveitaspecialobject filecalledalibrary.Orperhapsyou’vebuiltalibraryofcodethatyou’dliketo useagainandagain,butdon’twanttorecompileeachtimeyouusethecode. Byaddingalibraryofpre-compiledcodetoyourproject,youcansavesome timeandgainimmediateaccesstoaworldofsolutions.
Figure2-2.Projectwithmultiplesourcefiles
Building Your Application
Xcodestartsbycompilingmain.candextras.c sourcefiles,showninFigure2-2,turningthemintoobjectcode.Next,allthreeobjectfilesarelinkedtogether bythelinkertocreatearunnableapplication.Theprogramsinthisbookwereall designedtorunintheconsolewindow.Asyoumakeyourwaythroughtherest ofthebooksinthisseries,you’lllearnhowtoaddtherestofthepieces
necessarytocreateapplicationsthatcanberunfromtheFinder.Fornow, Xcode’sconsolewilldojustfine.
Thisentireprocess---turningsourcecodeintoafinishedprogram---iscalleda build.Xcode’sbuildcommandtakescareofallofthedetailsforyou.It
determineswhatcompilersyouneed,keepstrackofthelibrariesyourcodelinks to,findsaplacetostorealloftheintermediatefilescreatedbythecompilers andlinkers,andkeepsthosefilesorganizedandup-to-date.
What’s Next?
Atthispoint,don’tworrytoomuchaboutthedetails.Thebasicconceptto rememberfromthischapterishowyourCprogramsrun:theystartlifeas sourcecodeandthengettranslatedintoobjectcodebythecompiler.Finally,all theobjectcodegetslinkedtogethertoformyourrunnableapplication.
3
Chapter
CBasics:Statements
andFunctions
Everyprogramminglanguageisdesignedtofollowstrictrulesthatdefinethe language’ssourcecodestructure.TheCprogramminglanguageisnodifferent. ThesenextfewchapterswillexplorethesyntaxofC.Thischapterfocuseson twooftheprimarybuildingblocksofCprogramming:statementsandfunctions. Inanutshell,astatementtellsthecomputertodosomething.Afunctionisa seriesofstatements.
C Statements
AstatementinCisverymuchlikeadeclarativestatementinEnglish;ittellsthe computertodosomething.‘‘Say‘Hello’’’and‘‘preheatovento350°F’’are examplesofconcise,unambiguous,Englishstatements.Herearetwo statementsintheClanguage:
printf( "Hello!\n" ); temperature = 350;
Thefirststatementtellsthecomputertomakethetext‘‘Hello!’’appearonthe console(similartowhatyousawinChapter2).Thesecondstatementtellsthe computertoassignthevalue350toavariablenamedtemperature.C
C Functions
ACfunctionisagroupofCstatements.Therearemanyreasonsfororganizing statementsintoafunction,buttheprimaryreasonforgatheringstatementsinto asinglefunctionistomakethemeasilyreusable.
Acakerecipeconsistsofmanyindividualsteps:‘‘siftflour,’’‘‘addeggs,’’ ‘‘preheatoven,’’‘‘spreadicing,’’andsoon.Byorganizingthesestepsintoa largerentity,arecipe,wecannowsimplysay‘‘bakeacake,’’insteadof repeatingalloftheindividualsteps.
Similarly,aCfunctionisasequenceofCstatements,thewholeofwhichcanbe invokedasaCstatement.(Readthatagain,slowly.)Youcreateyourown functionsinClikethis:
void SayHello( void ) {
printf( "Hello!!!\n" ); }
YoujustcreatedafunctionnamedSayHello(),whichdoesonething.Itconsists ofasinglestatementthatcallsanotherfunction,namedprintf(),thatoutputsa messagetotheconsolewindow.
CONSOLE
Technically,thefunctionprintf()sendsitsoutputtosomethingcalledstandardoutputand Xcoderedirectsstandardoutputtoitsconsolepane.You’lllearnmoreaboutstandardoutputin Chapter9whenwediscussthecommandline.Forthemoment,justthinkofprintf()asa functionthatsendsinformationtotheconsole.
NOTE:Throughoutthisbook,we’lldesignateafunctionbyplacingapairof parenthesesafteritsname.Thiswillhelpdistinguishbetweenvariablenamesand functionnames.Forexample,thenamedoTaskreferstoavariable(variablesare coveredinChapter4),whiledoTask()referstoafunction.
thedetailsofhowprintf()works,anymorethanyouneedtorememberallof thestepsinvolvedinbakingacakeyoubuyfromyourlocalbakery.Youorder thecakeandthechefgoesthroughthestepstobakeit.YoucalltheSayHello() functionanditgoesthroughthestepstomake‘‘Hello!’’appearintheconsole.
Defining a Function
Functionsstartoffwithafunctiondeclaration,inthiscase:
void SayHello( void )
Afunctiondeclarationconsistsofareturntype,thefunctionname,andapairof parentheseswrappedaroundaparameterlist.We’lltalkaboutthereturntype andparameterlistlater.Fornow,theimportantthingistobeabletorecognizea functiondeclarationandbeabletopickoutthefunction’snameinthe
declaration.
Followingthedeclarationcomesthebodyofthefunction.Thebodyisalways placedbetweenapairofcurlybraces:{and}.Thesebracesareknownin programmingcirclesasleftcurlyandrightcurly.Here’sthebodyofSayHello():
{
printf( "Hello!!!\n" ); }
Thebodyofafunctionconsistsofaseriesofstatements.Thisparticular
statementcallsanotherfunction,butthereareotherkindsofstatements,too.As youmakeyourwaythroughthisbook,you’lllearnallofthedifferentkindsofC statements,andwhatthey’reusedfor.
Creatingefficientstatementswillmakeyourprogramsrunfasterwithless chanceoferror.Themoreyoulearnaboutprogramming(andthemoretimeyou spendatyourcraft),themoreefficientyou’llmakeyourcode.
Syntax Errors and Algorithms
WhenyouaskXcodetocompileyoursourcecode,thecompilerdoesitsbestto translateyoursourcecodeintoobjectcode.
compilercomplainsandwon’tcompileyourprogram.You’llexploreseveral commonkindsofsyntaxerrors,andfixthem,laterinthischapter.
Thesecondtypeofmistakeisasemanticerror,oraflawinyourprogram’s algorithm.Analgorithmistheapproachusedtosolveaproblem.Youuse algorithmsallthetime.Forexample,here’sanalgorithmforsortingyourmail:
1. Startbytakingthemailoutofthemailbox. 2. Ifthere’snomail,you’redone!GowatchTV. 3. Takeapieceofmailoutofthepile.
4. Ifit’sjunkmail,throwitaway,andgobacktostep2. 5. Ifit’sabill,putitwiththeotherbills,andgobacktostep2. 6. Ifit’snotabillandnotjunkmail,readit,andgobacktostep2.
Thisalgorithmcompletelydescribestheprocessofsortingthroughyourmail. Noticethatthealgorithmworks,evenifyoudidn’tgetanymail.Noticealsothat thealgorithmalwaysendsupatstep2,withtheTVon.
Figure3-1showsapictorialrepresentationofthemail-sortingalgorithm, commonlyknownasaflowchart.Muchasyoumightuseanoutlinetoprepare forwritinganessayortermpaper,youmightuseaflowcharttofleshouta program’salgorithmbeforeyouactuallystartwritingtheprogram.Here’show thisworks.
Thisflowchartusestwotypesofboxes.Therectangularboxportraysanaction, suchastakingmailoutofthemailboxorrecyclingthejunkmail.Onceyou’ve takentheaction,followthearrowleadingoutoftherectangletogoontothe nextstepinthesequence.
Eachdiamond-shapedboxposesayes/noquestion.Unliketheirrectangular counterparts,diamond-shapedboxeshavetwoarrowsleadingoutofthem.One showsthepathtotakeiftheanswertothequestioninsidetheboxisyes;the othershowsthepathtotakeiftheanswerisno.Followtheflowchartthrough, comparingittothealgorithmdescribedpreviously.
IntheCworld,awell-designedalgorithmresultsinawell-behavedprogram.On theotherhand,apoorlydesignedalgorithmcanleadtounpredictableresults. Suppose,forexample,youwantedtowriteaprogramthataddedthreenumbers together,printingthesumattheend.Ifyouaccidentallyprintedoneofthe numbersinsteadofthesumofthenumbers,yourprogramwouldstillcompile andrun.However,theresultoftheprogramwouldbeinerror(youprintedone ofthenumbersinsteadofthesum)becauseofaflawinyourprogram’s algorithm.
Theefficiencyofyoursourcecodeisadirectresultofgoodalgorithmdesign. Keeptheconceptofalgorithminmindasyouworkyourwaythroughthe examplesinthisbook.
Calling a Function
InChapter1,youranatestprogramtomakesureXcodewasinstalledproperly. Thetestprogramsatinafilecalledmain.candconsistedofasinglefunction, calledmain().Asarefresher,here’sthesourcecodefrommain.c:
#include <stdio.h>
int main(int argc, const char * argv[]) {
// insert code here... printf( "Hello, World!\n" ); return 0;
}
Thoughsomepartsofthisprogrammightseemintimidating,hopefullysome partsofitshouldstarttofeelfamiliar.
There’sreallyonlyonelineinthiscodethatyouneedtofocusonatthispoint, andthat’sthisfunctioncall:
Thoughthisprogramdoeshaveafewcomplicated-lookingelements,atitsheart isasinglefunctioncall.Asfarasalltheotherdanglybits,youcanreadthe‘‘Five EasyPieces’’sidebar,orjustignorethemandknowthatwe’llgettothemaswe goalong.
Sowhatdoes‘‘callingafunction’’reallymean?Basically,wheneveryoursource codecallsafunction,eachofthestatementsinthecalledfunctionisexecuted beforethenextstatementofthecallingfunctionisexecuted.
Confused?Don’tworry,you’llgetthere.LookatFigure3-2.Inthisexample,
main()startswithacalltothefunctionMyFunction().ThiscalltoMyFunction() willcauseeachofthestatementsinsideMyFunction()tobeexecuted,oneafter theother.OncethelaststatementinMyFunction()isexecuted,controlis returnedtomain().Next,main()callsAnotherFunction().Oncethelast
statementinAnotherFunction()isexecuted,controlisagainreturnedtomain(), andmain()canthenexitwithareturncodeof0.Whenmain()exits,your programexits.Returningavalueof0tellswhateverprogramlaunchedyour programthatallisOKandthatyourprogramisdone.
Figure3-2.main()callsMyFunction().AllthestatementsinMyFunction()areexecuted.Once
MyFunction()returns,main()thencallsAnotherFunction().
EveryCprogramyouwritewillhaveamain()function.Yourprogramwillstart runningwiththefirstlineinmain()and,unlesssomethingunusualhappens,end withthelastlineinmain().Alongtheway,main()maycallotherfunctionswhich may,inturn,callotherfunctionsandsoon.
FIVEEASYPIECES
Here’sabitofbehind-the-scenestechnicaldetailforfolkswhowantamorecompletepictureof thesourcecodewejustexplored.Skimthroughthisexplanationand,ifitseemsabitfuzzy, comebacktoitlateron.Bythetimeyougettotheendofthebook,thiswillallseempretty straight-forward.
Thesourcecodeinmain.ccanbebrokenintofivebasicpieces.Here’sthefirstpiece:
#include <stdio.h>
InC,anylinethatstartsoffwithapoundsign(#)isknownasapreprocessordirective,an instructionthatasksthecompilertodosomethingspecial.Thisparticulardirectiveiscalleda
#include(pronounced“poundinclude”).Itasksthecompilertoincludecodefromanotherfile onyourharddriveasifthatcodewasinthisfileinthefirstplace.A#includefileisalsoknown asaheaderfileorjustplainheader.Asitturnsout,thefilestdio.hcontainsallkindsofgoodies thatyou’llusethroughoutthebook.Justignorethislinefornow.
Here’sthesecondpiece:
int main (int argc, const char * argv[]) {
}
Asdiscussedabitearlier,thisisthefunctiondeclarationforthefunctionnamedmain().The curlybracessurroundthebodyofthefunction.
Thethirdpieceofthispuzzleisthisline:
// insert code here...
Anytimethecompilerencounterstwoslashes(//)inarow,itignorestheslashesandanything elseonthatline.Thislineofcodeiscalledacomment.Itsonlypurposeistodocumentyourcode andtohelpmakeclearwhat’sgoingonatthispointintheprogram.Commentsareagoodthing. Thefourthpieceisthecalltothefunctionprintf(),whichwewillfocusoninthischapter.
printf( "Hello, World!\n" );
Thefifthandfinalpieceofyourprogramisthislineofcode:
return 0;
Areturnstatementinafunctiontellsthecompilerthatyouaredonewiththisfunctionandyou wanttoreturn.Inthiscase,youwantthefunctiontoreturnavalueof0.
Same Program, Two Functions
Asyoustartwritingyourownprograms,you’llfindyourselfdesigningmany individualfunctions.Youmightneedafunctionthatputsaformuponthe screenfortheusertofillout.Youmightneedafunctionthattakesalistof numbersasinput,providingtheaverageofthosenumbersinreturn.Whatever yourneeds,youwilldefinitelybecreatingalotoffunctions.Let’sseehowit’s done.
Yourfirstprogramcontainedafunctionnamedmain()thatpassedthetext string‘‘Hello,world!\n’’toprintf().Yournextprogram,Hello2,embedsthat
functionalityinanewfunction,namedSayHello().
NOTE:You’veprobablybeenwonderingwhythecharacters\nkeepappearingatthe endofthetextstrings.Don’tworry;nothing’swrongwithyourcopyofthebook.The
\nisperfectlynormal.Ittellsprintf()tomovethecursortothebeginningofthe nextlineinthetextwindow,sortoflikepressingtheReturnkeyinatexteditor.
Thesequence\nisfrequentlyreferredtoasanewlinecharacter,acarriagereturn, orjustplainreturn.Byincludinganewlineattheendofaprintf(),youknowthat thenextlineyouprintwillappearatthebeginningofthenextlineintheconsole window.
The Hello2 Project
Figure3-3.Hello2workspacewindow
Theareawiththegraybackgroundonthetopoftheprojectwindowiscalled thetoolbar.Thetoolbarcontainsavarietyofconvenientshortcuts,whichyou cancustomizetosomedegree.
Theareabelowthetoolbarisdividedintoaseriesofpanes.Ontheleftsideof theprojectwindow,you’llfindthenavigatorpane.Theiconsatthetopofthe navigatorpaneallowyoutonavigatetodifferentareasofyourproject.By default,theprojectnavigatoriconshouldappear.Theprojectnavigatorlistsall thefilesandfoldersthatmakeupyourproject.
Thecentralareaistheeditorpaneand,belowit,thedebugpane.Selectafilein theprojectnavigatoranditwillopenforeditingintheeditorpane.Whenyourun yourproject,you’llmakeuseofthedebugarea.That’swheretheconsolelives. Totherightoftheeditorpaneistheutilitypane.Theutilityarealetsyou customizevariouselementsinyourprogramandisespeciallyusefulwhenyou startaddingobjectstoyourprogramsasyoumoveontoObjective-C,Cocoa, andCocoaTouch.
Ontherightsideofthetoolbar,you’llfindthreesetsofcontrols,labeledEditor, View,andOrganizer.ThethreeViewbuttonsallowyoutoshoworhidethe navigator,debug,andutilitypanes,asyouplease.Youcan’thidetheeditor pane---that’salwaysthere.Thecommandsforswitching,revealing,andhiding thesepanescanallbefoundintheViewmenu.
theoneshowninFigure3-3),chooseViewNavigatorsShowProjectNavigator. NoticetheCsourcecodefilenamedmain.cintheprojectnavigator’slistoffiles. Ifyouclickonmain.c,thesourcecodewithinthefilewillappearintheeditor pane.
NoticetheProductsfolder,belowtheHello2folder.Thisiswhereyourfinished program(i.e.the‘‘product’’ofthisproject)willappearonceyou’vesuccessfully builtit.Ifit’sred,yourprogramhasn’tbeenbuiltyet.
TIP:Wanttolearnmoreabouttherestoftheitemsintheprojectnavigator?Apple hasanexcellentXcodemanualbuiltrightintoXcode.ChoosetheHelpXcodeUser Guidecommand.Theveryfirstpageexplainsthepartsoftheworkspacewindow, withlinksthatexplaineachofthevariousnavigators,editors,andutilitiesingreat detail.We’llgiveyoujustenoughinformationaboutXcodeinthisbooktogetyou throughlearningC,butifyoueverwanttoexploreXcodemore,justpulluptheXcode UserGuideanddigin.
The Hello2 Source Code
Here’sthesourcecodefrommain.c:#include <stdio.h> void SayHello( void );
int main (int argc, const char * argv[]) {
SayHello(); return 0; }
void SayHello( void ) {
printf( "Hello, world!\n" ); }
Let’swalkthroughthislinebyline.Hello2startsoffwiththislineofsourcecode:
#include <stdio.h>
aregoingtocallprintf()inthissourcecodefile.You’llseethe#include pre-processordirectiveusedthroughoutthisbook.Getusedtoseeingthislineof codeatthetopofeachofyoursourcecodefiles.
Thelinefollowing#includeisblank.Thisiscompletelycool.SincetheC compilerignoresallblanklines,youcanusethemtomakeyourcodealittle morereadable.Weliketoleavetwoblanklinesbetweenfunctions.
Thislineofcodeappearsnext:
void SayHello( void );
Whilethislinemightlooklikeafunctiondefinition,don’tbefooled!Ifthiswerea functiondefinition,itwouldnotendwithasemicolon;itwouldbefollowedbya leftcurly({)andtherestofthefunction.Thislineisknownasafunction prototypeorfunctiondeclaration.You’llincludeafunctionprototypeforevery function,otherthanmain(),inyoursourcecodefile.
Tounderstandwhy,ithelpstoknowthatacompilerreadsyoursourcecodefile fromthebeginningtotheend,alineatatime.Byplacingacompletelistof functionprototypesatthebeginningofthefile,yougivethecompilerapreview ofthefunctionsitisabouttocompile.Thecompilerusesthisinformationto makesurethatcallstothesefunctionsaremadecorrectly.
NOTE:Functionprototypeswillmakealotmoresensetoyouonceyougetintothe subjectofparametersinChapter7.Fornow,getusedtoseeingfunctionprototypes atthebeginningofallyoursourcecodefiles.
Nextcomesthefunctionmain().Thefirstthingmain()doesiscallthefunction
SayHello().
int main (int argc, const char * argv[]) {
SayHello();
Atthispoint,thelinesofthefunctionSayHello()getrun.WhenSayHello()is finished,main()canmoveontoitsnextlineofcode.Thekeywordreturntells thecompilertostopexecutingstatementsandreturnavalueof0(zero)tothe functionthatoriginallycalledmain().We’lltalkaboutreturnlateron.Untilthen, theonlyplaceyou’llseethislineisattheendofmain().
Followingmain()aresomemoreblanklines,followedbythefunctionyou created,SayHello().SayHello()printsthestring‘‘Hello,world!’’,followedbya return,inawindow,andthenreturnscontroltomain().
void SayHello( void ) {
printf( "Hello, world!\n" ); }
Let’sstepbackforasecondandcomparethefirstprogramtoHello2.Inyour firstprogram,main()calledprintf()directly.InHello2,main()callsafunction thatthencallsprintf().ThisextralayerdemonstratesabasicCprogramming technique:takingcodefromonefunctionandusingittocreateanewfunction. Thisexampletookthislineofcode
printf( "Hello, world!\n" );
andusedittocreateanewfunctioncalledSayHello().Thisfunctionisnow availableforusebytherestoftheprogram.Everytimeyoucallthefunction
SayHello(),it’sasifyouexecutedthislineofcode:
printf( "Hello, world!\n" );
SayHello()maybeasimplefunction,butitdemonstratesanimportantconcept. Wrappingachunkofcodeinasinglefunctionisapowerfultechnique.Suppose youcreateanextremelycomplexfunction,say,100linesofcodeinlength.Now, supposeyoucallthisfunctioninfivedifferentplacesinyourprogram.With100 linesofcode,plusthefivefunctioncalls,youareessentiallyachieving500lines’ worthoffunctionality.That’saprettygoodreturnonyourinvestment!
Let’swatchHello2inaction.
Running Hello2
InXcode,runyourprogram.DothisbyclickingontheRunbuttoninthetoolbar, choosingtheProjectRuncommand,orpressing⌘R.ThisasksXcodetocompile allofyoursourcefiles(yes,alloneofthem),linktheobjectcodetogetherto formanexecutableprogram,andrunthatprogram.
You’llseethedebugareaappearbelowyoursourcecode.Ontherightisthe consoleoutput,asshowninFigure3-4.Ifyoudon’tseethis,choosetheView DebugAreaActivateConsolecommandorpress⇧⌘C.
Figure3-4.TheresultofrunningHello2
Beforeyoumoveontoyournextprogram,let’srevisitalittleterminologywe firsttouchedonatthebeginningofthechapter.Thepaneinthedebugareathat appearedwhenyouranHello2isreferredtoastheconsolepane,orjustplain console.TherearenumerousStandardLibraryfunctionsdesignedtosendtext totheconsole;you’reusingprintf().Thetextthatappearsintheconsoleis knownastheprogram’soutput.Afteryourunaprogram,you’relikelytocheck theoutputthatappearsintheconsoletomakesureyourprogramrancorrectly.
THESTANDARDLIBRARY
OneelementoftheCstandardthatrelatesdirectlytoourdiscussionoffunctionsistheStandard Library.TheStandardLibraryisasetoffunctionsavailabletoeveryCprogrammer.Asyoumay haveguessed,theprintf()functionyousawinthesamplesourcecodeispartoftheStandard Library,asaretonsofothergreatfunctions.You’lllearnsomeofthemorepopularonesasyou makeyourwaythroughthisbook.OnceyougetcomfortablewiththeStandardLibraryfunctions presentedhere,digthroughsomeoftheStandardLibrarydocumentationthatyou’llfindonthe Web,justtogetasenseofwhatelseisinthere.
AnumberofgreatsitesdiscusstheStandardLibrary.Oneofourfavoriteresourcesonthenetis theWikipediaentryfortheANSICStandardLibrary
(http://en.wikipedia.org/wiki/ANSI_C_standard_library
).
Thispageisaterrific waytogettoknowtheStandardLibrary.There’salotofinterestinginformationhere,butthe bestpartisthetabletitled“CStandardLibraryheaders.”Itcontainsalinktoeachofthe StandardLibrary#includefiles.Eachlinktakesyoutoapagethatdescribesthefunctions includedinthatparticularheaderfile.Forexample,clickthestdio.hlink.Wow,theresureareatonoffunctionsinthisheaderfile.If youscrolldownabit,you’llfindalinktoapagethatdescribestheStandardLibraryfunction printf().Followthatlink,andyou’llcometoapagethatcontainsjustabouteverythingyoucould everwanttoknowaboutprintf().
Doing That Again, and Again, and Again
ImaginewhatwouldhappenifyouchangedHello2’sversionofmain()sothatit readasfollows:
int main (int argc, const char * argv[]) {
SayHello(); SayHello(); SayHello();
return 0; }
What’sdifferent?Inthisversion,you’veaddedtwomorecallstoSayHello(). Canyoupicturewhattheconsolewilllooklikeafteryourunthisnewversion? Tofindout,closetheHello2projectwindow,andthenselectOpenfromXcode’s Filemenu.WhenXcodepromptsyoutoopenaproject,navigateintotheLearn CProjectsfolderandthenintothe03.02-Hello3subdirectory,andopenthe Hello3.xcodeprojprojectfile.
WhenyourunHello3,theconsolepaneshowninFigure3-5willappear.Takea lookattheoutput.Doesitmakesensetoyou?EachcalltoSayHello()
generatesthetext‘‘Hello,world!’’followedbyacarriagereturn.
Generating Some Errors
Beforeyoumoveontothenextchapter,let’sseehowthecompilerrespondsto errorsinyoursourcecode.IntheHello3projectwindow,selectmain.csothe sourcecodeappearsintheeditingpane.
Inthesourcecodewindow,findtheSayHello()functiondefinition.Notethatthe definitionofafunctioniswhereyouactuallyprovidethefunctionbody.A
functiondeclarationdoesnotincludecurlybraces.Afunctiondefinitiondoes includecurlybraces.Gotit?Good!Thefunctionshouldread
void SayHello( void ) {
printf( "Hello, world!\n" ); }
Clicktotherightoftheprintf()statement,sotheblinkingcursorappearsjust afterthesemicolonattheendoftheline.Deletethesemicolon,sothelinenow reads
printf( "Hello, world!\n" )
RememberthatinC,aregularCstatementendswithasemicolon,andyoujust leftitout.ThisislikeforgettingtheperiodattheendofasentenceConfusing, isn’tit?YoursourcecodenolongerfollowstherulesestablishedintheC99 standard.Thisiscalledasyntaxerror.Lookbackatyoursourcecode.Itshould looklikethewindowinFigure3-6.
Figure3-6.Xcodedetectsasyntaxerror
Whileyouaretyping,agroupofelves---OK,technicallyXcode’s‘‘liveissues’’ checker---isconstantlyre-evaluatingyoursourcecodetoseethatmeetsallof therequirementsforcorrectCsyntax.Ifitdoesn’t,itimmediatelyputsanerror (orwarning)indicatorinyoureditingwindowat,ornear,whereitthinksthe problemis.
Fixing the Problem
Figure3-7.IssuedetailandFixItsuggestion
Clickingonanissueinthegutterdisplaysadditionalinformationaboutthe problem,oratleastXcode’sinterpretationofwhatitthinkstheproblemis---we’ll gettothatinamoment.
Inthiscase,Xcodecorrectlydeterminedthatyouomittedthesemicolon requiredattheendofaCstatement.ItevenincludesaFixItbuttonthatoffers tocorrecttheproblemforyou.Double-clicktheFixItbutton,andXcodeinserts therequiredsemicolon,andtheissuedisappears.
Beforethedaysofautomaticsyntaxchecking,programmerswouldn’tdiscovers errorslikethisuntiltheytriedtocompiletheirsourcecode.Ifyougivethose elvesawell-deservedbreak(byturningoff‘‘liveissues’’featureintheXcode preferences),youwon’tfindoutaboutthesekindsofproblemsuntilyoucompile yourcode.Leavethesemicolonoutandtrytorun(ProjectRun)yourprogram again.Itdoesn’trun.Instead,youreceivea‘‘Buildfailed’’messageandthe error,onceagain,appearsinyoursourcecode.You’llalsoseetheerrorinthe outputofthelatestbuildlog(ViewNavigatorsShowLogNavigator)andinthe issuesnavigator(ViewNavigatorsShowIssueNavigator). Theissuesnavigator
keepsarunningtabofalloftheproblemsXcodehasknowsabout,inone convenientlocation.
Getting Close
‘‘Closeonlycountsinhorseshoesandhandgrenades,’’astheoldsayinggoes. Somedaytheymightadd‘‘compilers’’tothatlist.
Let’stryadifferentkindofmistake.Thistime,gotothefunctiondefinition(not thedeclaration,right?).Addasuperfluoussemicolonattheendofthatline,so yourcodenowlookslikethis:
void SayHello( void ); {
Figure3-8.Anothersyntaxissue
Thistimetheerrormessageis‘‘Expectedidentifieror‘(‘’’.Thatdoesn’tsound veryhelpful,andthere’snoFixItbuttonthistime.
Alotoftimesthecompilercan’ttellyouwhat’swrongwithyourcode,onlythat itdoesn’tfollowtherulesfortheClanguage.Inthiscase,thecompilerlooksat thefirstlineofthefunctionandassumesit’safunctiondeclaration---remember thatadeclarationendsinasemicolon,whileadefinitioncontainsafunction body.Thecompilercan’tknowthatwhatyoudidwasaddanextrasemicolon whereitdoesn’tbelong.Itonlyknowsthere’safunctiondeclarationfollowedby somethingelsethatshouldn’tbethere.
Thetake-awaymessageisthatthecompilercan’talwaystellyouexactlywhat themistakeis,orevenexactlywhereitis.Startbylookingforaproblem immediatelybeforewherethecompilercomplains.Insomecasestheactual mistakewillbesomeplaceelseentirely,eveninanothersourcefile.Withsome experience,andalittlepractice,you’llgetgoodatfiguringoutwhattheproblem isandhowtofixit.
Speakingofwhich,deletethatstraysemicolonsoeverythingcompilesagain. You’vegototherkindsofmistakestomake!
C is Case Sensitive
AnotherverycommonmistakeresultsfromthefactthatCisacase-sensitive language.Inacase-sensitivelanguage,thereisadifferencebetweenlowercase anduppercaseletters,whichmeansyoucan’trefertoprintf()asPrintf()or evenPRINTF().
Let’strythisout.Double-click‘‘printf’’inyoursourcecodetoselectit,engage theCapsLockonyourkeyboard,andtype‘‘PRINTF’’.Whoa!Whathappened? DoesyourscreenlooklikeFigure3-9?