Learn C on the Mac, 2nd Edition
A complete course on C programming for the beginner
- • • • • • • • •
Learn C on the
Mac For OS X and iOS
SECOND EDITION David Mark James Bucanek |
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
iv
ContentsataGlance
AbouttheAuthors ............................................................................... AbouttheTechnicalReviewer............................................................. Acknowledgments................................................................................ Introduction......................................................................................... Chapter1:GoGettheTools!.................................................................. Chapter2:ProgrammingBasics ......................................................... Chapter3:CBasics:StatementsandFunctions ................................. Chapter4:CBasics:VariablesandOperators .................................... Chapter5:Debugging.......................................................................... Chapter6:ControllingYourProgram’sFlow ...................................... Chapter7:PointersandParameters................................................. Chapter8:MoreDataTypes.............................................................. Chapter9:TheCommandLine .......................................................... Chapter10:DesigningYourOwnDataStructures ............................ Chapter11:WorkingWithFiles......................................................... Chapter12:HandlingErrors.............................................................. Chapter13:AdvancedTopics............................................................ Chapter14:WhereDoYouGofromHere?......................................... Appendix:AnswerstoExcercises ..................................................... Index..................................................................................................
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. NoteDouglasAdamswasabigMacintoshfan.Onceyougetthroughthisbook,you’llbereadytomoveontoobject-orientedprogramming andObjective-C—theofficialprogramminglanguageofOSXandiOS. Doesthisallsoundalittleoverwhelming?Nottoworry;inthisbook,we’lltakesmallsteps,so nobodygetslost.Youcandefinitelydothis!
WhoIsThisBookFor? WhenDavewrotetheveryfirsteditionofLearnContheMacbackin1991,hewaswritingwith collegestudentsinmind.Afterall,collegewaswherehereallylearnedtoprogram.Itseemshe waswayoff. xvi
INTRODUCTION “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.
Chapter6introducestheconceptofflowcontrol,usingconstructslikeif,else,do,and whiletocontrolthedirectionyourprogramtakes.
Chapter7coverspointersandparameters,twoconceptsthatwilladdadramaticnew levelofpowertoyourprograms.
Chapter8movesbeyondthesimpledatatypesusedinthefirsthalfofthebook, addingtheabilitytoworkwithmorecomplexnumbersalongwithdatatypeslike arraysandtextstrings. xvii INTRODUCTION Chapter9takesabreaktoshowyouhowtodeployyourfinishedprogramanduseit fromthecommandline.
Chapter10divesevendeeperintodataandteachesyouhowtodesignyourown customdatastructures.
Chapter11showsyouhowtosaveyourprogram’sdataandreaditbackinagainby introducingtheconceptofthedatafile.
Chapter12givesyousometechniquesfordealingwitherrors,forwhenthingsgo wrong.
Chapter13coversavarietyofadvancedtopics—typecasting,unions,recursion, sorting,collections,andmuchmore.
Finally,Chapter14wrapsthingsupandpointsyoutothenextsteponyourjourney. Readytogetstarted?Let’sgo! xviii
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.
NOTE:Anapplicationthatorganizesmultipledevelopmenttoolsintoasingle
workspaceiscalledanintegrateddevelopmentenvironment(IDE).XcodeisanIDE. 1 CHAPTER1:GoGettheTools!
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. registereddevelopers.Becoming ItusedtobethatXcodewasonlyavailableto aregistereddeveloperusuallycostsmoney,soXcodewas‘‘free’’onlyinthe sensethattheprizeinsideacerealboxis‘‘free.’’ Forawhile,Xcodewaspricedat$5.Asofthiswriting,XcodeisfreeintheApp Store.Hopefully,itwillstaythatway.
CHAPTER1:GoGettheTools! 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 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). willneedtobecomearegistereddeveloperifyouwanttosell,orevengive You away,yourmasterpiecesonanyofApple’sappstores.Howcoolwouldthatbe? Youcanregisteratanytime,sothere’snohurry.Whenyouareready,visit
CHAPTER1:GoGettheTools!
Getting the Projects
Whileyou’restillwaitingforXcodetodownloadandinstall,whynotgetthe projectfilesforthisbook?Everythingyouneedtocreatetheprojectsinthis bookisdescribedinthetext,butdownloadingthefinishedprojectsfromthe Apresswebsitewillsaveyoualotoftyping. GotoBelowthebook’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
OnceXcodehasfinishedinstalling,launchitasyouwouldanyapplication,from thedockorLaunchPad.Whenfirstlaunched,Xcodewillpresentitsstartup window(Figure1-2).
CHAPTER1:GoGettheTools!
Figure1-2.Xcodestartupwindow
Thestartupwindowhasconvenientbuttonsthatcreateanewproject,reopena recentlyvisitedproject,linktotheXcodedocumentation,andsomeotherstuff we’renotgoingtocoverinthisbook. project.Aprojectisacollectionoffilesthat Xcodeorganizesyourworkarounda ultimatelyproduceaprogram.Italwaysconsistsofa projectdocument(theicon withthelittleblueprint)storedinsideafolder,asshowninFigure1-3.Thatfolder projectfolder.Youopenaprojectbyopeningtheproject iscalledthe document.
CHAPTER1:GoGettheTools!
Figure1-3.ThecontentsofasimpleXcodeprojectfolder
workspacewindow,asshown WhenopenedinXcode,yourprojectappearsina inFigure1-4.Thewindowisfullofcrypticsettingsandseeminglycomplex controls,butdon’tworry.Untilyougettosomereallyadvancedprogramming, youwon’tneedtofiddlewithanyofthesesettings.
Figure1-4.AworkspacewindowinXcode
Creating a New Xcode Project
WhileXcodestillhasthat‘‘newcarsmell,’’let’stakeitforaquickspinaround theblockandcreateanewXcodeproject. CreateanewXcodeprojectlinkinthe
Todothis,eitherclickonthelinklabeled startupwindow,orchooseFileNewProjectfromthemenubar.You’llbe
CHAPTER1:GoGettheTools!
newprojectassistant,showninFigure1-5,whichwillhelp presentedwiththe youspecifythetypeofnewprojectyouwanttocreate.
Figure1-5.Newprojectassistant
Theleftsideofthenewprojectassistantletsyouchoosewhethertocreatea projectforiOS(onethatwillrunonyouriPhone,iPad,oriPodtouch)orforMac ApplicationintheMacOSX
OSX(onethatwillrunonyourcomputer).Select section. Next,youneedtodecidethetypeofMacOSXapplicationyouwanttobuild.In thisbook,you’regoingtolearnhowtobuildsimple,text-onlyapplicationsthat displaytextinawindow,onelineatatime.Onceyoufinishthisbook,youcan moveontobooksthatwillteachyouhowtousetheskillsyou’vejustmastered tobuildapplicationsthatwillrunonyouriOSdeviceoronyourMacwiththe graphicalelementsthatdefinethosedevices. Select CommandLineToolfromthetemplatespane.Thisistheonlyproject
Next templateyou’llbeusinginthisbook.Tocompleteyourselection,clickthe button. CHAPTER1:GoGettheTools!
Thenextscreen(Figure1-6)letsyounameyournewprojectandspecifyafew Hello otheroptions.Foracommand-linetooltheoptionsareprettysimple.Enter inthe Namefield.
CompanyIdentifierallowsXcodetospecifywhomadethisapplication. Thefield Typically,thisisareverseofadomainnameyou’vesetupforyourproduct. Unlessyou’vegotaspecificidentifieryouwanttouse,useonewe’vesetupfor com.apress.learncintheCompanyIdentifierfield. thisbook.Enter
Figure1-6.Projecttemplateoptions
Typepop-upmenutoC,sinceyou’llbewritingallyourprogramsinthe Setthe Cprogramminglanguage. AutomaticReferenceCountingdoesn’tapplytoC.Leavethe UseAutomatic ReferenceCountingcheckboxunchecked. Nowthatyouroptionsareallset,clickthe Nextbutton. Finally,Xcodewillpromptyouforalocationinwhichtosaveyourprojectfolder. Thoughyoucansaveyourprojectsanywhereyoulike,youmightwanttofirst
CHAPTER1:GoGettheTools!
MyLearnCProjects,inwhichyoucan createamasterfolder,perhapsnamed 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
Atthebottomyou’llfindthedebugarea,whichnormallyappearsonlywhile you’rerunningortestingaprogram.Thisiswhereyouinspectyourprogram whileit’srunningandviewitsoutput.Attheverytopisthetoolbar.Ithas
Runbuttonattheleft buttonsandcontrolsforthingsyoucommonlydo.Thebig willbuildandrunyourprogram,whichiswhatit’sallabout.Everythinginthe toolbarisjustashortcutforacommandintheXcodemenubar;itdoesn’tmatter whichyouuse. CHAPTER1:GoGettheTools!
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! Thenextchapterwilltakeabreakfromallofthisexcitementtotalkaboutthe softwaredevelopmentprocessingeneral.
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
DinosaurToday. month’sissueof Whatevertheirpurpose,eachoftheseexamplessharesacommontheme.They areallexamplesoftheartofprogramming.Yourgoalinreadingthisbookisto learnhowtousetheCprogramminglanguagetocreateprogramsofyourown. BeforewegetintoC,however,let’stakeaminutetolookatsomeotherwaysto solveyourprogrammingproblems.
11 CHAPTER2:ProgrammingBasics
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?
Thereisaconstantdebateastowhichprogramminglanguageisthebestoneto learnfirst.Naturally,theC++peoplethinkthatC++isbyfarthebestlanguage tostartwith.Java,C#,andObjective-CpeoplefeelthesamewayaboutJava, C#,andObjective-C.ButthetruthisthatallofthoselanguagesarebasedonC. AndifyoulearnCfirst,you’llhaveahugeleguponlearninganyofthem.And
CHAPTER2:ProgrammingBasics
whenthenextC-basedlanguagehitsthestreets,you’llhavealeguponthat one,aswell. Inanutshell,Cisthebestlanguagetostartwithbecausemanyotherlanguages usethevastmajorityofC’ssyntaxandstructure.Objective-C,C++,andJava eachstartwithCandbuildonC,eachinitsownuniqueway.LearningCfirstis likelearningtowalkbeforelearninghowtorun.IfyoulearnCfirst,you’llhavean excellentfoundationonwhichtobaseyourfutureprogrammingeducation.
What’s the Best Programming Language for the Mac or iOS Devices?
Alltheprogramsinthisbookwillrunintheconsole,asimplescrollingtext windowthatispartofXcode.Ifyouwouldliketobuildapplicationsthatfeature theMaclook-and-feelwithbuttons,scrollbars,andwindows,you’llneedto finishthisbook,thenlearnObjective-CandCocoa(fortheMac)orCocoaTouch (foriOSdevices). Objective-CisaprogramminglanguagebasedonC.Everythingyoulearnabout objects. CwillapplytoObjective-C.Objective-Cisdesignedtoworkwith Objectsareblocksofcodethatrepresentpartsofyourprogram,suchasa scrollingwindow,animage,oramenu.Cocoaisavastcollectionofobjectsthat representalltheelementsoftheMacexperience.Objective-Cwasdesignedto worktogetherwithCocoaandCocoaTouch. LearnC,Objective-C,andCocoa,andyouwillhaveeverythingyouneedto developeventhemostcomplexMacintoshapplications.LearnC,Objective-C, andCocoaTouch,andyouwillhaveeverythingyouneedtodevelop applicationsdesignedtorunonmobiledevicesrunningiOS. LearnContheMacisthebeginningofaseriesofbooksthatwillteachyouhow tobuildprofessionalMacandiOSapplications.Onceyou’vefinishedthisbook, nd you’llwanttodiginto LearnObjective-ContheMac,2 EditionbyMark
Dalrymple,ScottKnaster,andWaqarMalik(Apress2012).Itwasdesignedasa LearnContheMacanddoesagreatjobtakingyoufromCto sequelto
Objective-C. LearnCocoaontheMacwaswrittenbyJackNutting,DaveMark,andJeff LaMarche(Apress2010).Itcompletesthecycle,givingyoueverythingyouneed tobuildyourownscrollable,clickableMacapplications. IfyouareinterestedinbuildingapplicationsthatrunontheiPhone,iPodtouch, oriPad,checkout BeginningiOS6DevelopmentbyDaveMark,JackNutting, andJeffLaMarche(Apress2012). BeginningiOSDevelopmentwasalsowritten
CHAPTER2:ProgrammingBasics
LearnObjective-C.InsteadoffocusingonCocoa,though,it asasequelto focusesonCocoaTouch. So,first,finishthisbook,andthenmakeyourwaythrough LearnObjective-Con theMac.IfMacapplicationdesignisyourgoal,nextpickupacopyofLearn CocoaontheMac.IftheiPhone,iPodtouch,oriPadisyourthing,pickup BeginningiOSDevelopment. Andthat’stheroadmap.Oh,onemorething.Youcanfindeachofthesebooks ontheApresswebsiteat
The Programming Process
InChapter1,youinstalledtheMacdevelopmenttoolsandwentthroughthe processofcreatingaproject,whichyouthenbuiltandran.Let’stakealookat theprogrammingprocessinabitmoredetail.
Source Code
sourcecode.Your Nomattertheirpurpose,mostcomputerprogramsstartas sourcecodewillconsistofasequenceofinstructionsthattellsthecomputer whattodo.Sourcecodeiswritteninaspecificprogramminglanguage,suchas syntax)that C.Eachprogramminglanguagehasitsownsetofrules(called defineswhatisandisn’tlegalinthatlanguage. Yourmissioninreadingthisbookistolearnhowtocreateuseful,efficient,and, bestofall,legalCsourcecode. IfyouwereprogrammingusingeverydayEnglish,yoursourcecodemightlook likethis:
‘‘Hi,Computer!Dome afavor.Takethenumbersfrom1to10, addthemtogether,andthentellmethesum.’’
Ifyouwanttorunthisprogram,youneedaprogrammingtoolthatunderstood sourcecodewritteninEnglish.Sadly,computersdon’tunderstandEnglish(yet). Instead,youmustuseapreciselanguage,likeC,toexplaintothecomputer exactlywhatyouwantittodo.Listing2-1isanexampleofcodethatsums numbers1through10.
CHAPTER2:ProgrammingBasics 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-1showstheworkspacewindowforSample.xcodeproj.Thewindowisa complexbeast,fullofincrediblyusefultoolstohelpwithyourprogramming pursuits.Themostimportantpartoftheprojectwindow(atleastforthe moment)istheeditingpane,theareathatallowsyoutoedityoursourcecode.
CHAPTER2:ProgrammingBasics Figure2-1.TheSampleprojectworkspace
Runbuttoninthetoolbar,bychoosingthe Runtheprogrambyclickingthe ProjectRuncommand,orbytyping
⌘R. Theprogramshouldbuildandthenrun,andthetextweshowedyoupreviously shouldappearintheconsolepane.Ifyoudon’tseetheconsolepane,choose theViewDebugAreaShowDebugAreacommand. OK,enoughreveling.Let’sgetbacktotheprogrammingprocess.
Compiling Your Source Code
compiler. Onceyoursourcecodeiswritten,yournextjobistohanditofftoa ThecompilertranslatesyourCsourcecodeintoinstructions------asequenceof numericcodes------thatmakesensetoyourcomputer.Theseinstructionsare machinelanguageorobjectcode.Sourcecodeisforyou;machine knownas language/objectcodeisforyourcomputer.Youwritethesourcecodeusingan editor,andthenthecompilertranslatesyoursourcecodeintoamachine- readableform. CHAPTER2:ProgrammingBasics NOTE:Don’tlettheterminologybogyoudown.Readtherestofthischapter,justto
getabasicsenseoftheprogrammingprocess,andthenmoveontoChapter3.We’ll layouteverythingstep-by-stepforyou,soyouwon’tgetlost. Thinkoftheprocessofbuildingandrunningyourprogramasathree-stage process.First,Xcodecompilesallyoursourcecodeintoobjectcode.Next,all linkerto theobjectcodeinyourprojectislinkedtogetherbyaprogramcalleda formyourapplication.Thatfinishedapplication(calledan executable)iswhat actuallyrunsonyourcomputer. TakealookatFigure2-2.Thisprojectcontainstwosourcecodefiles,one namedmain.candanothernamedextras.c,aswellasanobjectfilenamed
libc.dylib.Sometimes,you’llfindyourselfmakinguseofsomecodethat
othershavealreadycompiled.Perhapstheywanttosharetheircodebutdonot wanttoshowyoutheirsourcecode.ThisisthewayApplemakestheircode availabletoprogrammers.Theycompilethecodeandsaveitaspecialobject library.Orperhapsyou’vebuiltalibraryofcodethatyou’dliketo filecalleda useagainandagain,butdon’twanttorecompileeachtimeyouusethecode. Byaddingalibraryofpre-compiledcodetoyourproject,youcansavesome timeandgainimmediateaccesstoaworldofsolutions. Asitturnsout,alibrarycalledtheCStandardLibrarycomeswithXcodeand everyotherCdevelopmentenvironmentintheuniverse.Hmm,thatmustbewhy theycallit‘‘standard.’’TheCStandardLibrarycomespackedwithanincredible numberofusefulprogrammingbitsandpiecesthatyoucanuseinyourown programs.(Thislibraryissocommonlyusedyoudon’tevenhavetoaskXcode toincludeitinyourproject;itjustdoessoautomatically.)We’lltalkaboutthose bitsandpiecesaswemakeuseofthemthroughoutthebook.
CHAPTER2:ProgrammingBasics
Figure2-2.Projectwithmultiplesourcefiles
Building Your Application
Xcodestartsbycompilingmain.candextras.csourcefiles,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. ThegreatthingaboutXcodeisthatyou’llprobablyneverhavetoconcern yourselfwithanyoftheseunder-the-hooddetails.Youjustwriteyoursource
Runbutton.Xcodewilltakecareoftherest. codeandpressthe
CHAPTER2:ProgrammingBasics
What’s Next?
Atthispoint,don’tworrytoomuchaboutthedetails.Thebasicconceptto rememberfromthischapterishowyourCprogramsrun:theystartlifeas sourcecodeandthengettranslatedintoobjectcodebythecompiler.Finally,all theobjectcodegetslinkedtogethertoformyourrunnableapplication. Now,let’sgettothebusinessofwritingyourveryfirstCprogram.
3 Chapter CBasics:Statements andFunctions