291

Introduction to C_C__ With SFML - Robert Cook

Embed Size (px)

DESCRIPTION

fsd

Citation preview

  • IntroductiontoC/C++ProgrammingwithSFMLforfun

  • v1.3RobertP.CookJanuary1,2015

    dedicatedtoKristina,Kimberley:Luke:Molly:Alex,Thomas:Joseph,Amanda:Eli,Nicholas,Jana:Kate,Peter

    DisclaimerofLiability:Theauthormakesnowarranty,expressorimplied,includingthewarranties ofmerchantability and fitness for a particular purpose, or assumes any legalliabilityorresponsibilityfortheaccuracy,completeness,orusefulnessofanyinformation,apparatus, product, or process disclosed, or represents that its use would not infringeprivatelyownedrights.

    Foreword:Thechaptershereinhavebeenusedasclassnotesformanyyears. Thewebsiteprofessorcook.orgcontainson-linetestsandaudiolecturesthatcomplementthetext.Please send any corrections or suggestions to [email protected]. You can alsoemail the address to request a free copy of the example programs.Thank you for yourpurchase.

    OneoftheadvantagesofaKindleisthatpurchaserscanupgradetonewversionsastheybecome available. Each new revisionwill have a higher version number and the bookEditionNumberatAmazonwillbeupdated.Todownloadanewversion,deletethebookfrom theKindle usingContentManager. Then select the book inContentManager todownloadtomemory.ThelatestversionwillbedownloadedfromAmazon.

  • QUICKACCESS

  • CHAPTER ONE HARDWARE &OPERATINGSYSTEMSCHAPTER TWO CONSTANTS ANDEXPRESSIONSCHAPTERTHREESTATEMENTSCHAPTER FOUR PREPROCESSORMACROSCHAPTERFIVEPROCEDURESCHAPTERSIXDEBUGGINGCHAPTERSEVENARRAYSCHAPTEREIGHTSTRINGSCHAPTERNINEPOINTERSCHAPTER TEN STRUCTURES ANDUNIONSCHAPTERELEVENC++CHAPTERTWELVEFILESCHAPTERTHIRTEENWHATNEXT?ASCIITABLESBINARY,OCTAL,HEXADECIMAL

  • TABLEOFCONTENTS

  • CHAPTER ONE HARDWARE &OPERATINGSYSTEMSIntroductionPartsofaComputerPartsofanOperatingSystemApplicationloadingandexecutionPermanentstoragefordataandprogramobjectsControlledsharingandprotectionofinformationSupportforstandardApplicationProgrammingInterfacesFileanddirectorynamingDirectoriesAbsolutepathnamesLinkingNameresolution

    CommandsHelpcommandSimplecommandMultiplecommandsDetachedcommandsWildcardnamingI/OredirectionPipesShellProcedures

  • PartsofaCommandWhatdoesacompilerdo?Howtomakeacommand?

  • CHAPTERTWOCONSTANTSANDEXPRESSIONSIntroductionConstantsLineSyntaxExpressionsFormulasandTablesTablesWithDecimalPointsBigTables

  • CHAPTERTHREESTATEMENTSIntroductionVariablesDeclarationsChangingavariableAssignmentStatement

  • ConditionalStatementBooleanexpressionsShort-circuitevaluationAssertmacro

  • IFstatementArithmeticIf__builtin_expect

  • SwitchStatementWhileStatementsBreakandContinueStatementsArithmeticAssignmentStatementsForStatementsGotoStatementsandlabelsVariableStorageExternvariables

  • SFMLforFun

  • CHAPTERFOURPREPROCESSORMACROSIntroduction#include#define#undef#if#pragma

  • CHAPTERFIVEPROCEDURESIntroductionArgumentsandParametersProcedurePrototypesOldCPrototypesVectorConceptsCurvesExampleRecursionProcedureParametersUsefulCFunctions

  • CHAPTERSIXDEBUGGINGIntroductionWolf-TrapDebuggingExaminingProgramStateGUIDebuggers

  • CHAPTERSEVENARRAYSIntroductionParametersAlgorithmsSearchingBinarysearch

  • SortingParticlesVarying-LengthArgumentLists

  • CHAPTEREIGHTSTRINGSIntroductionStringAPIsCollationandLocalesInternationalization

  • UnicodeSprintf_sandSscanf_s

  • CHAPTERNINEPOINTERSIntroductionDynamicStorageAllocationPointerArithmeticTypeCastsSortingandSearchingArraySlicesMulti-dimensionalArraysVarying-LengthArgumentLists

  • CHAPTERTENSTRUCTURESANDUNIONSIntroductionTypedefStructuresBottom-upProgrammingTop-DownProgrammingInformationHidingOpaquetypes

  • ProceduresUnionsBitVariablesShiftingandMasking

  • ListsIterators

  • AbstractDataTypesVariablelifetimemodelTransparentInterfaceDesign

  • CHAPTERELEVENC++IntroductionACAbstractDataTypeAC++AbstractDataTypeUnitTestingUnittestcreation

  • ChainingInheritanceC++StandardLibraryExceptionsTemplatesVirtualFunctionsC++TypeCasts

  • CHAPTERTWELVEFILESIntroductionLinuxLinuxobjectsDirectoriesDevicesVolumes

    ProtectionTheSystemCallLevelCreatingandconnectingtofilesFileoperationsAsynchronousI/O

    DirectoryoperationsStatusandcontroloperationsThe/procfilesystem

    Kernelcaching

  • TheCLibrary

  • CHAPTERTHIRTEENWHATSNEXT?Introduction

    ASCIITABLESBINARY,OCTAL,HEXADECIMAL

  • PROGRAMSSFMLCircles(acircle)Constants(bconstant)Expressions(coperator)SFMLShapes(dcolorshape)SquaresandCubes(esquares)Centigrade(fcents)Centigrade/FahrenheitTable(gtable)SFMLCircleLoop(hcircles)DataTypes(iconst)Scanf(jread)Assignment(kassign)Argv(lcommand)CtoFCommandLine(mcommand)AssertMacro(nassert)TriangleTest(otriangle)SalesCommission(pcar)WhileLoop(qfives)ForLoopSFMLBounce(rbounce)GotoSFMLMouseandKeyboard(sdemo)SFMLAnimation,Fonts,Sound,Music(sdemo2)SFMLSpritesandConvexShapes(sdemo3)SubroutineFunctionMax(a,b)SFMLLines(tline)SFMLCurves(ucurve)FactorialNumericalIntegration

  • AckermanFunctionCallStackArrayprintf/scanfUnorderedSearchSearchBenchmark(vsearch)BinarySearchSelectionSortInterchangeSortQuicksortSFMLParticles(wparticle)UnicodeTemperaturesprintf/sscanfPointersDynamicArrayInputSizeofQsortandBsearchSubstringSortingMatrixMultiply(xmatrix)VarArgsEnumeratedTypeTemperatureADTStep1TemperatureADTStep2Bottom-UpProgrammingBitFieldsShiftandMaskSingly-LinkedListListsprintf/sscanf(ylist)Doubly-LinkedListListIteratorOpaqueRectangleClass(zarectopaque)BouncingRectangles(zcrectmover)TransparentRectangleClass(zbrectclass)C++HelloWorld

  • C++RectangleClassC++MultipleInheritanceC++ExceptionsC++TemplatesC++VirtualFunctionsSFMLUser-DefinedShapes(sdemo4)SFMLTileSetEditor(sdemo5)SFMLGameView(sdemo6)

  • CHAPTERONEHARDWARE&OPERATINGSYSTEMS

    IntroductionThisbookteacheshowtounderstandCandC++programsandplaces thereaderonthepathtobecomingaCandC++programmer.TryingtolearnC++withoutfirststudyingCis likebecominganoar expertwithout ever seeing a canoe. Since theC language is asubsetoftheC++language,theexamplescanbecompiledandexecutedusingMicrosoftVisualStudio,OS/XXCode,orLinuxg++.

    The author has written over half a million lines of code in forty-five years ofprogramming. The textassumes thatyouarefamiliarenoughwithacomputer toeditafileandtoinstallaC++compileronaPC,MacorLinux.Otherthanthat,conceptsareexplainedfromthegroundup.

    Why learn C? First, it is an international standard. ISO/IEC JTC1/SC22/WG14 is theinternationalstandardizationworkinggroupfortheprogramminglanguageC.ThecurrentCprogramminglanguagestandardISO/IEC9899wasadoptedbyISOandIECin1999.TechnicalcorrigendaTC3wasapprovedin2007.ISO/IEC14882:2011istheinternationalstandardforC++.

    The Linux operating system is written in C. C++ and Java systems are written in C.MicrosoftsoperatingsystemsarewritteninC.EventhefirstC++compilerwaswrittento translate C++ statements into C statements. There are hundreds of thousands of Cprograms and libraries on the Internet. However, themost important reason to learnCfirstisthatitwasoriginallydesignedtooperateasclosetomachinelevelaspossible.Theobservation is that a good knowledge of low-level C provides a great foundation tounderstandhowmodernhigh-levellanguageswork.AftercoveringtheCfeatures thataresubsumedinC++,thebookpresentsthenewC++syntaxandsemantics.

    ACOMPILERistheapplicationthatturnsabunchofwordsandsymbolsinaCprograminto an executable application. On Apple computers, the programming environment(Xcodewithgcc)isavailableforfreetoanyonewhoregistersasadeveloper.OnLinuxsystems,thecompilerisgccandcomesinstalledwiththeoperatingsystem.OnMicrosoftcomputers, the options are to install an express edition of Visual Studio (Google freevisual studio or check dreamspark.com), to installCygwin (Linux forwindows, henceincludesgcc), toinstallagcc-for-windowspackage,or touseaproduct likeVMwaretoinstall a free Linux, such as Fedora from redhat.com, as a virtual appliance on yourcomputer.AllthebooksexamplesarecompiledusingC++.

    SFML(SimpleandFastMultimediaLibrary)byLaurentGomilaprovidesasimpleC++interface to the various components of your computer, to facilitate the development ofgames and multimedia applications. It is composed of five modules: system, window,graphics (based on OpenGL), audio and network. SFML is multi-platform:Windows,OS/X,Linux.

  • PartsofaComputerComputerinformationisstoredandmanipulatedinBINARYBITsthatonlyhaveavalueofzero(0)orone(1).ASTORED-PROGRAMusesthesamebitsofmemory(butnotatthe same time) to store the instructions to the computer (add, subtract etc.). TheCENTRAL-PROCESSING UNIT (CPU) retrieves instructions from memory toexecute.NotethatanADDinstructioncannotbeexecutedwithoutknowingwhattoadd;thus,theCPUalsofetchestheADDinstructionsoperandsfrommemory.

    Modern CPUs consist of several ALUs (integer arithmetic-logic units, add (3+4),subtract), anFPU (floating-point (or real number) unit, add (0.31+4.8732), subtract), aCACHE (holds copies ofmemory values for fast access by other units), an instructionsequencing unit, and a virtual-memory unit (supports the use of a disk to extend thememory capacity). Modern CPUs are SUPER-SCALAR (execute several arithmeticoperations simultaneously) and PIPELINED (execute steps of several instructionssimultaneously). Obviously, if a CPU executes data as an instruction or treats aninstructionasdata,amachinefaultoccurs.Similarly,itisaerroriftheALUoperatesonarealnumber(0.31)ortheFPUoperatesonawholenumber(3).Notethatinacomputertheinteger3isstoredinmemoryasadifferentsequenceofbitsthantherealnumber3.0.

    Tolowercosts,moderncomputershavecentralizedmostof theelectroniccircuitryonasingleprinted-circuitboard,whichisreferredtoasaMOTHERBOARD.AllthebitsthataretransferredamongtheCPU,memoryandI/OdevicestravelbyBUS.I/OstandsforINPUT/OUTPUT. Typical I/O devices include a storage disk, headphones, DVD orBluRaydisk,mouse,keyboardanddisplay.ABUSisanalogoustoasuper-highwaywithmultiple lanes. By increasing thenumberof lanes,ahighwaycansupportmore traffic.The transfer rate (bandwidth, usually expressed as megabits/second) of a BUS isdeterminedbyitswidth(1,8,32,64or128)bitsandthespeed-of-lightpropagationtimeforabittotravelfromoneplacetoanother.Megameansmillion.

  • The usefulness of a computers memory is determined by its storage capacity and itsaccesstime(rangesfrom2nanosecondsto2microseconds).Thefourvarietiesofmemoryfound in most computers are ROM (read-only), EEPROM (electrically erasableprogrammable read-only or FLASH), SRAM (static read-alterable), and DRAM(dynamicread-alterable).ROMisthecheapest.Itcanonlybewrittenonceusingaspecialexternal electrical device. The BIOS (basic input-output software) for PCs is stored inROM.TheBIOSisusedforlow-leveldevicecontrolandtoinitializethecomputerwhenitisturnedon.FLASHisusedonthebetterPCsandhand-helddevicestoallowtheBIOSorOPERATINGSYSTEMtobeupgraded.FLASHhasthenicepropertythaterroneousinstructionscanneverchangeit(nohacking).

    DRAMisusedinthelargestquantitiesbecauseitischeap,butithasthepropertythatitforgets everything once power is removed. Thus, all important instructions (like theoperatingsystemcommands)anddatamustbekeptonDISK.TheprocessofBOOTINGa computer initializesDRAMwhen power is turned on by reading its previous contentfromDISK. SRAM is themost expensive because it holds its values even if power is

  • turnedoff.MostcomputersonlyhaveasmallamountofSRAM.

    MemoryAddressing

    AllMEMORYisjustabunchofbits;however,bitsaretypicallygroupedeightatatimetoformaBYTE.Also, eachBYTEhasan index (orADDRESS, like a house address)thatcanbeusedtoretrieveorsetitsvalue.Thus,anADDRESS(orindex)of50intotheaddressrange[0,1,2,,47,48,49,50]wouldaccessthe51stbyte(remembercountingstartsat zero) inmemory.The following table lists the namesused to refer to other commongroupingsofbits.

    GroupsofBytesName(1Byte==8b)1bbit(0or1)8bbyte(B)2Bshortinteger4Binteger8Brealnumber1024Bkilobyte(KB)1024KBmegabyte(MB)1024*1024KBgigabyte(GB)1024*1024*1024KBterabyte(TB)1024*1024*1024*1024KBpetabyte(PB)

    DiskDrive

  • Anything stored on a disk drive stays there until it is physically erased. Disks mustusuallybeformattedpriortouse.RememberthatDRAMforgetsitscontentswhenpoweris turned off and that booting restores that content from DISK. The SHUT-DOWNprocedureinanoperatingsystemMUSTbeexecutedpriortoturningoffpowertomakesurethattheDRAMcontentisproperlysavedonDISK.

    A video card, or chip set, implements common display operations, such as drawing acharacter, line, polygon, or circle. Each card has a certain amount ofmemorybuilt-in,which is used to accelerate graphic operations and to free main memory for otherpurposes. Performance is sometimes expressed in the number of triangles drawn persecond.ThetermRENDERINGisusedtodescribetheprocessoftakinga3Dsceneandmathematically projecting it onto a flat 2D surface (the display). Common displaytechnologiesareLED(light-emittingdiode)andLCD(liquid-crystaldisplay).

    A video display is a rectangle composed of lines of dots or pixels (picture elements),whicharestoredinaframebuffer. Amonochromedisplayonlyshows2colorsperdot(black/white).Thevideocardscansaframebuffersothateachdotonthescreenissettothecorrectcolor;4giga-colorsrepresents232possibilities.

    FrameBuffer

  • Inadditiontographics,adisplaypaintscharacters,suchastheonesthatyouarereading.CharactersaregroupedintoFONTfamilies.Intheolddays,eachcharacterinafontwascarved in a block of wood. Typesetting a newspaper involved arranging the woodencharactersinalargeframethatwascoatedwithinkandstampedonablanksheetofpaper.Display font characters are stored as a block (rectangle) of bits. When needed, eachrectangleiscopied(BLiTed(blocktransfer))tovideomemory.Inthepast,eachcharacter(abAB)ineachfontrequireditsowndefinitionrectangle,whichresultedinthousandsofdefinitionsforeverycombinationofsize/family/language(12pixel/Times/Arabic) thatauser might want. Today TrueType technology uses mathematics to define a singledescriptionofeachfontfamilythatcanbescaledlargerorsmallerarbitrarily.

    ThefollowingTrueTypeletterAwouldneed1000sofbytestostoreitsimage,butifyouexamine its outline, there are only four curves, two ofwhich are symmetric. Thus, bydescribingthestraightlines(twoendpoints)andthecurveparameters,anAofanysizecanbedrawn.TheletterintheFigurewasdrawnwithafontsizeof640.

  • Colorseemslikeasimpleconcept.Thethreekindsofphoto-receptorsinthehumaneyerespond most to yellow, green and violet light. The difference in the signals receivedenablesthebraintodifferentiateawiderangeofcolors,beingmostsensitivetoyellowish-greenlightandtovariationsinhuesinthegreen-to-orangeregion.

    ThemostcommoncomputercolormodelisRGB,whichcombinesRed,GreenandBluetoencodeacolor.Typically,thevaluesareencodedas0to255with(0,0,0)asblackand(255,255,255)aswhite. Notethat thebinaryrangeofnumbers thatcanbestoredinabyte is 000000002 to 111111112 (0 to 255). Since writing long strings of bits iscumbersomeanderrorprone,programmershaveadopted thehexadecimal (base16, seetheAppendix) number system to represent computermemory, 0016 toFF16 (0 to 255).Hexadecimal is preferred because each hex digit (0-9 andA B CD E F) represents 4binarybits.

    Remember that renderingprojects a 3D sceneonto a 2Dmatrix of pixels in theGPUsframebuffer.Tomaketheresultmorerealistic,itisdesirabletohavecolorvalueswithanaddedtransparencycomponent.ObservethatRGBisstoredin3bytes;the4thbytestoresatransparencycode(0invisible,to255opaque),whichistypicallydenotedbytheletterA.Asaresult,mostframebuffersallocate4bytesforeachpixel.A640pixel(wide)by480(high)displaywith32-bitcolorwouldneed640*480*4Bor1.2MBofmemory.

    TopRectangleisPartiallyTransparent

  • AMOUSE,stylusorfingertransmitshorizontalandverticalmovementstotheoperating

    system,whichusestheinformationtomoveaCURSOR(abitpattern) aroundthedisplay.Mice have from one to three buttons and sometimes a scroll wheel. You canmove themouse tomove thecursor andclickabutton (typically the left-most) to set ablinkingCARET ( | ) thatmarks the text position atwhich youwant to begin/resumetyping. Mobiledevices typicallydonot implementcursors,butmayhave sophisticatedgesturesupport.

    Akeyboard iscomposedofmanybuttons thatcanbedepressed tocommunicatewithaPROGRAM. Every time the user presses or releases a button, a SCANCODE istransmitted to the operating system. Sequences of scan codes are translated by theoperatingsystemeithertoASCIIorUNICODE.ACODE(likeasecretcode) is justanassociationof human symbolswithnumbers.Theuseof scanCODESallows the samekeyboard to be sold in many different countries because it is the operating systemsresponsibilitytotranslatethescancodetoanativelanguagecharacter.ForexampleintheU.S.,ascancodeof00011110translatestotheletterAora(dependingontheSHIFTkey).

    Note that a keyboard contains keys (CAPS-LOCK or CTRL) that do not display as acharacterandkeyswhosesolepurposeistochangethecharacterdisplayed(SHIFT-a==A).

    The two universal character codes are ASCII and UNICODE. ASCII is the AmericanStandardCodeforInformationInterchange.ASCIIassociatesallupper/lowercaseletters,digits, and punctuation marks with a 7-bit number. For example, the number code 48representsthe0(zero)symbol.

    UNICODE is a 32/16-bit character code that includes symbols for all the worldslanguages, mathematics, and ASCII. The 32/16-bit UNICODE number for all ASCIIcharactersisidenticaltothe7-bitASCIInumber.Notethataddingleadingzerosdoesnotchangethevalueofanumber.

  • TheEnterkey isused to indicate thatyouhave finished typinga lineof text. UpuntiltypingEnter,youcanpresstheBackspacekeytodeletepreviously-typedcharacters.Howdoesthecomputerknowwhenyouhavefinishedtypingcompletely?WhatifyoutypeD(thephoneringsanditsmom)thenOG?Howdoesthecomputerknowwhenyouwillreturn? The answer is that every operating system defines a special key sequence toindicate I-am-finished-typing. In Windows, the sequence is CTRL-z; in Linux, it isCTRL-d.

    Whatifyourunaprogramanditwillnotstoporitlocksup?InWindows,youcantypethe famous CTRL-ALT-DEL (3-finger salute). In Linux, CTRL-c will kill an errantprogram. On an Apple, Force Quit will do the trick. Finally, many Graphical-User-Interface (GUI) programs like Microsoft Excel or Word use key combinations asaccelerators (or short-cuts) for longer actions or to avoid menu selection. On manysystems,CTRL-pmeansprint-document.

    AnOPERATINGSYSTEM, such as Linux, is the control software that executes userPROGRAMSorAPPLICATIONS.Iftheprogramisacomponentoftheoperatingsystem(LinuxorWindowsorOS/X),itiscalledaCOMMAND.MostoperatingsystemsincludeaCOMMAND INTERPRETER (or shell) that allows users to enter character (text)commandlinesinteractively(i.e.printprogram).Often,aGUI(graphicaluserinterface)isprovidedthatdisplaysicons(apicturethatrepresentsanapplicationspurpose).Typically,movingthecursoroveraniconandthenclickingabuttonwillcausetheoperatingsystemtoexecutetheprogramorcommandassociatedwiththeicon.

    APROGRAMisasequenceofinstructionsforaCPUandincludesthedatavaluesthattheinstructionsmanipulate.Mostprogramsaretranslatedfromahigh-level,user-friendlylanguage,suchasC thatuseshumanwords (i.e.add3 to4), into thebits that representCPUinstructions(add)anddatavalues(3or4.75).

  • PartsofanOperatingSystemRememberwepromisedthatthebookstartsfromfirstprinciples.First,wediscussedtheparts of a computer. Now we discuss the parts of an operating system, particularlycommandexecutionandnaming.Why?TheClanguagewasnotdevelopedinavacuum.Itwas designed in order to implement the predecessor of Linux,UNIX, atAT&TBellLaboratories.Assuch,UNIX/LinuxandCweredesignedtobesymbiotic.TounderstandC, andmany featuresofmodernoperating systems, youneed an introduction toLinux;thatisthegoalofthisSection.

    Without an operating system, compilers, assemblers, editors, and especially applicationprogramsarelargelyuseless.

    AnOPERATINGSYSTEM(supervisor,monitor,executive)managestheuseofhardwareresourcesbyapplications.Typical resourcesarecomputer time,memoryanddiskspace,anddevices.Anoperatingsystemusuallyprovidesanumberofthefollowingservicestoitsusercommunity.

    OperatingSystemServices

    1.Applicationloadingandexecution2.Permanentstoragefordataandprogramobjects3.Controlledsharingandprotectionofinformation4.SupportforstandardApplicationProgrammingInterfaces(APIs)

    5.ElectronicmailandotherInternetservices6.AllocationandschedulingofCPU,memory,anddeviceresources7.Multimediaservices8.Reliabilityandfailurerecovery

    ApplicationloadingandexecutionAuser application canbe as simple as 3+4or as sophisticated as avideo editor. Anapplication can be comprised from nativemachine instructions or can consist of non-native instructions, inwhichcase theapplicationmustbe interpreted.Typically,ausers

  • systemhasmanyhundredsofapplications installedinsecondarystorage. Eachmustbeloadedintomemorypriortoexecution.

    The components of an application are its instructions (code), data (initialized anduninitialized),resources(icon,strings,controls, imagesetc.)andoftenasymboltableofnamesusedintheprogram.Onwindow-basedsystems,anICONisthepicturethatcanbeusedtoactivateanapplication.Youmightwonderwhystrings(text)areresourcesandnot initializeddata. ThereasonisINTERNATIONALIZATION.Byfactoringtextoutofaprogram, itcanbeadaptedfordifferent languageswithoutmodifying theprogram.Controls are window components such as dialogs, list boxes, menus, and buttons. Asymbol table is used for symbolic debugging or profiling or for remote access to aprogramsdata.

    PermanentstoragefordataandprogramobjectsTheabilitytoexecuteaprogramisnotveryusefulunlesstheresultcanbesaved.Also,asthenumberofsavedobjects increases, theability tocatalogandretrieveobjectsquicklybecomesmore important.Justasofficesusedeskorganizersandfilecabinets,operatingsystems must create their electronic counterparts to help programmers organize andmanipulate information. The term object is used to reflect the increasing diversity ofsaved information e.g. speech, graphics, character fonts, VLSI designs, and databaserecords.

    ControlledsharingandprotectionofinformationWhendata or devices are accessible bymore thanoneprogram, controlled sharing andprotectionisrequired.Controlledsharingcanrangefromnoaccesstoaccessonlybyaspecifiedlistofusers.Otherprotectionoptionsmightbetospecifythefrequencyortimeofuse,themodeofuse,ordeletionoptions.Possibleaccessmodesmightberead-only,append-only,write-only,execute-only,oranycombinationofthese.

    SupportforstandardApplicationProgrammingInterfacesAninterfaceisacollectionofusefulmethods.Forexample,theMathinterfaceincludesthetrigonometricmethodssine,cosine,tangentetc.Totakethesineofanangle,theanglecanbeexpressedindegreesorradians.Shouldaninterfaceprovidebothmethods?Whataboutanglesexpressedas integersversus realnumbers,singleversusdoubleprecision?Onecouldendupwithamyriadofmethods.

    OneofthedesigngoalsforaninterfaceistobeFUNCTIONALLYCOMPLETE;thatis,capable of computing any desired result. Thus, a sine function that takes an angle inradiansindoubleprecisionfloatingpointwouldbefunctionallycompletebecauseanglescanbeconvertedtoradians.

    AnAPIisacollectionofinterfacesinanapplicationdesign.APIstypicallyevolvefromyearsofexperienceandsomeinternationalarguing.APIscanbesubmittedforapprovalbynationalandinternationalstandardbodies.Theuseofastandardinterfaceinsoftwareisanalogoustotheuseofastandardinterfaceinhardware.Ethernetnetwork-plugsworkanywhereintheworld.Softwareshoulddothesame.OpenGLandtheClibraryarebothstandardAPIs.

  • FileanddirectorynamingProvidingtheabilitytostoreandretrieveprogramsanddataisacrucialfunctionofeveryoperatingsystem.TherepositoryfortheseobjectsiscalledaFILESYSTEM.Weusethetermobjectratherthanthetraditionaltermfiletodenotethemoremodernusesoffilesystemstorepresentsuchdiverseentitiesasspeechandvideodata,ports,pipes,devices,processes, and semaphores.Eachobjecthas anexternal,ASCIIorUNICODEname fortheconvenienceofhumans,aninternal identificationnumberforusebythefilesystem,andaphysicalrepresentationthatmustbestoredinsomephysicalcontainer.Linuxisusedastheprimaryexampleinthefollowingdiscussion.

  • Asanorganizationaltoolforhumans,filesystemsusuallyprovideDIRECTORIESthatcanbeusedtopartitionthesetofallobjects intorelatedsubgroups.Directoriesarealsoobjectsand,assuch,canalsobenamedbyauser.Forexample,userCookmighthaveadirectory named cook in which all his objects were stored. However, the cookdirectory might be further organized by the sub-directories books, programs,recipes,andtests.Eachof thesedirectoriescould, in turn,consistofanynumberofotherdirectories.Thepurposesofadirectoryaretomakeiteasytofindrelatedobjects,tocontrolaccesstotheobjects,andtomakesurethattheobjectyoufindistheoneyouwant.

    Asafurtherorganizationalaid,thedirectoriesofdifferentusersareusuallygroupedintologicalcontainers,calledVOLUMES.Avolumecanbethoughtofasafiledrawerwitheachfolderrepresentingadirectory.Ifadirectoryscontentissufficientlylarge,itisalsopossibletohavejustonedirectoryinavolume.

    TheLinuxfilesystemiscomposedoffilesandobjects.Afile issimplyanunstructuredstringofbytes.Anystructurethatisimposedonafilemustcomefromtheprogramsthatuseit.Atextfile,forexample,consistsofastringofcharacters,withlinesdelimitedbythenew-linecharacter.AfilecontainingaCprogramisexpectedtoconformtothesyntaxoftheClanguage.

    Unstructuredfilesaredangerousbecauseofthepotentialformisuse.Nothingpreventstheuser fromattempting to execute a source file, fromcompilingaCprogramwitha Javacompiler,orfromeditinganobjectmodule.Linuxaddressesthisproblembymaintainingnamingconventions.Thatis,eachfilenameisgivenasuffixthatindicatesitscontent.

    SYSTEMNAMINGCONVENTIONS

    NameInterpretation

  • x.cCprogramx.docInputtoawordprocessorx.oACprogramaftercompilingx.javaAJavaprogramx.shAshellprocedure

    Eachsubsystemisrequiredtofollowthenamingconventions;thus,iftheC++compilerisgivenafilethatdoesnothavethe.cppsuffix,itprintsanerrormessage.

    Directories

    Adirectory is a toolusedbyhumans toorganize information.Adirectory simplymapstext strings to internal file identification numbers. Unlike some other systems, Linuxallows names to be composed from any character except a NULL (00). Therefore, thelist program has to be careful to escape non-printing characters in file names.Otherwise,theprogrammermighthaveadifficulttimefindinganddeletingsuchfiles.

    Another Linux convention, enforced by the listing program, is not to list files that areprefixedwitha..Thesehidden filesareoftencreatedbysystemsprograms tosaveparameter information across log-in sessions. For example, the editor, shell, and mailprogramsmaintainhiddenfiles.Thefilesarehiddentokeepusersfromunintentionallydeletingthem.

    Absolutepathnames

    InLinux,thereisonedirectory,therootdirectory,thatcanbeusedtolocateanyfileinthesystembytracingapaththroughsuccessivesub-directoriesuntilthedesiredcomponentisfound.Byconvention,therootdirectoryhasthename/.

    When the name of a file is specified to the system, it may be in the form of anABSOLUTEPATHNAME, which is a sequence of directory names startingwith theroot directory, separated by slashes, /, and ending in a file name. Notice that theseparator symbol is the same as the name of the root directory. In some systems, theseparatorsymbolcanbealteredbymeansofasystemcall.

    ASAMPLEVOLUME

  • /alphaetcdeviceusersource

    betathetaeta

    gamma

    POSSIBLEABSOLUTEPATHNAMES:/(therootdirectory)/alpha/alpha/beta/alpha/theta/alpha/eta/alpha/beta/gamma/etc/device/user/source

    Linking

    Insomecases,itisconvenienttohavemorethanonenameassociatedwiththesamefile.This feature is called LINKING and a directory entry is sometimes called a LINK.Linkingmakes sharing easier and eliminates duplication of files. The file identificationnumberassociatedwitheachentryisreferredtoasanABSOLUTELINK.

    If file a is linked to an existing file b, the directory entries for both a and bcontainthesameinternalidentificationnumber.Anychangetothefileassociatedwiththename b is reflected in an identical fashion to programs that refer to the filewith thenamea.

    Asecondimplementationchoiceforlinkingistoassociateanamewithaliteralpathnamerather than a file number. This is termed SYMBOLIC LINKING. For example, thedirectory entry for gamma.lnkmight be associatedwith the string /alpha/eta ratherthanwithaninternalidentificationnumber.Withsymboliclinking,thelinkisboundtoan internal id on every reference; whereas in the former convention, the binding takesplacewhenthe link iscreated. ThetermBINDING isstandardterminologyinsystemsfortheprocessof,ortimeof,mappinganametoavalue.

    TheprogramthatcreatesdirectoriesisownedbytheSUPERuser,oradministrator,whohascompletecontroloveracomputer.Inadditiontocreatingadirectory,theprogramalsocreatestwoabsolutelinks,.and..toinitializethenewdirectory.Thename.referstothenewdirectoryitself.Thename..referstotheparentofthenewdirectory,thatis,to thedirectory inwhich it iscontained.Bothnamesareusedbyprograms thatneed torefertotheirexecutionenvironmentwithoutknowingabsolutepathnames.

    SYSTEM-CREATEDDIRECTORYLINKS

    /user/cook...notesbookclasses...chap1chap2

  • CURRENTDIRECTORY=/user/cook/book.=book..=cook../classes=classes../..=user

    The..linkconventionisalsousefulforcreatinglocation-independentsubsystems.Forexample, a program in the book directory could refer to chap1 by using ../notes.The cook directory and its content could then be relocated anywhere in the naminghierarchywithoutaffectingthevalidityof../notes.Nameresolution

    Theuseofabsolutepathnamesforfilesistoorestrictivetobetoleratedforverylong.ItismuchmorecommontousepathnamesthatareRELATIVEtosomepointinthedirectoryhierarchy.Forexample,anabsolutepathnamecanbeconsideredasrelative to theroot,/,ofthefilesystem.Thepreviousexampleusedrelativepathnames;thatis,.actuallywas equivalent to /user/cook/book/.Relativepathnames save a significant amount ofusertypingandimprovesystemefficiencybyreducingthenumberofdirectorysearches.

    Linuxsupports thenotionofaCURRENTorWORKINGdirectory that isusedas thedefault prefix for relative path names. It should be thought of as amarker that can bepositioned at any directory. It is set by the cd command.Any name presented to theoperating system that lacks the / prefix is appended to the current directory namebeforethenamesearchbegins.

    RELATIVEPATHNAMES

    /user/cook...notesbookclasses...chap1chap2

    CURRENTDIRECTORY=/user/cook/book

    NAMEPRESENTEDNAMESEARCHEDFORBYTHESYSTEM/user/cook/user/cook./user/cook/book/./chap1/user/cook/book/chap1

    Normally,eachprogrammerisalsoassignedaHOMEdirectorytoserveastherootofalldirectories createdby thatuser.Thehomedirectory isnormally specifiedaspartof thelogininformation.Afterloggingin,thehomeandcurrentdirectoriesarethesame.The user can then move the current directory pointer anywhere in the file systemhierarchybyusingasystemcommand,suchaschangedirectory.Attheshelllevel,thesymbol~representstheabsolutepathnameforthehomedirectoryofthecurrentuser.

    Eachuseriscapableofdirectlynamingfourcontexts,thesystemglobal/,thelocal.(also,thedefaultassumption),theuserglobalorhome~,andthelocallyenclosing...Incommonpractice,thesearenotsufficient.Forexample,supposethatmyCcompilerisin/user/cook/compiler/c.Tocompileaprogram,thecompilermustbeinvokedbyeither

  • itsabsolutepathnameorbyoneof thechoices for relativepathnames.A third,but farworse, alternative is to keep a copy of the compiler in every directory. The problem isevenmoreacuteforsystemsprograms,suchaseditorsorwordprocessors.Howisausersupposedtorememberthedirectoryinwhichtheeditorresides?

    Thesolutionis toprovideamechanismtoRESOLVErelativepathnames.Eachuser isallowed to specify a list of directories tobe searched to resolve a name.The followingexampleillustratesthesearchstepsforasamplelist.Noticethatthealternativesaretriedfromlefttoright.

    NAMERESOLUTIONWITHADIRECTORYSEARCHLIST

    SEARCHLIST:(.~/user/local/user/public/bin/etc)CURRENT:/user/cook/bookHOME:/user/cookTARGETNAME:aGoodTime

    DIRECTORIESSEARCHEDTOFINDaGoodTime:/user/cook/book/user/cook/user/local/user/public/bin/etc

    CommandsInalloperatingsystems,aCprogramisacommandthatcanbeexecutedthroughaterminalinterface.TheprogramthattalkstousersinaTerminalwindowisreferredtoasashell.ASHELLisaninterpreter;thatis,itallowsausertoexperimentwiththeoperatingsystemscommandsinaninteractivemanner.Keepinmind,though,thattheoperatorshavenameslikesearchandlistwhereastheoperatorsinatypicalinterpreter,suchasacalculator,wouldbe+and-.Theprinciplesarethesame;theapplicationistheonlydifference.Thefollowingexampleillustrateshowtheshellinterpretscommands.

    TheShellAsAnInterpreter

    /***PRINTTHEUSER-INPUTPROMPTSTRING***//***READACOMMANDLINE***//***FINDTHEPROGRAMCORRESPONDINGTOTHEGIVENCOMMANDNAME***//***INVOKETHEPROGRAMANDWAITFORITSCOMPLETION***/

  • OS/X,FedoraLinuxandMicrosoftShell/CommandWindows

    OS/X

  • Linux

  • Windows

    The Shell program is implemented as a closed loop that prints a prompt, waits forcommandinput,andexecutesthecommand.Thetexttakesasimpleexample,listingthenamesoffilesinthecookdirectory(containingfileschap1,chap2,chap3),andexpandsitasthevariousaspectsofshellprogrammingaredescribed.TheLinuxGNUBashshell(oneofmanyLinuxchoices)isusedfortheexamples.BashisintendedtoconformtotheIEEEPOSIXP1003.2/ISO9945.2ShellandToolsstandard..[gnu.org]

    Helpcommand

    Thefirstcommandtolearninanysystemistheonetofindhelp.Forexample,howcan

  • youfindthecommandthatdoeswhatyouwantifyoudonotknowitsname?Linuxhasbuiltin manual pages for all commands. The man command prints manual pages.Further, all proper Linux commands have a help option to tell the user aboutthemselves.ManycommandshaveacorrespondingGUIapplication.

    Simplecommand

    Thelscommandliststhefilesordirectoriesinthespecifieddirectory,inthiscasecook.Theargumentstoacommandareusuallystrings,notnumbersaswouldbetypicalwithanalgebraicinterpreter.Theargumentlistisimplementedasasingletextstring.Withinthestring,theargumentsaredelimitedwithblanks.Ifanargumentcontainsblanks,itmustbeenclosedinquotationmarks().Asanaside,anyGUIapplication,suchasawordprocessororspreadsheet,canbeexecutedbytypingitsprogramnameonacommandline.

    CommandArguments

    INPUTlscook

    OUTPUTchap1chap2chap3

    Theoutputindicatesthattherearethreeobjectsinthecookdirectory.

    Optionstocommandsusuallyprecedenamesandaredenotedbyaleading-.The-aoptionscausesthelscommandtoprinthiddenfilenames.Thus,eventhough.and..arepresentinthecookdirectory,theyarenormallynotlisted.InLinuxbydefault,.referstothecurrentdirectoryand..theparentdirectory.Again,thisconventionisnotbuiltintotheLinuxOSkernel.Anothersuchconventionistheuseof~torefertothecurrentusershomedirectoryor~cooktorefertothehomedirectoryofusercook.

    CommandOptionsArguments

    INPUTls-acook

    OUTPUT...chap1chap2chap3

    Infact,anyfilenamebeginningwitha.ishiddeninLinux.Therationalebehindthisdesign decision was to allow system commands to create hidden files for their ownpurposes. The files are not listed to protect them from deletion by novice users, who

  • would not normally be aware of their function. The hidden naming convention isimplemented external to the operating system, which conforms to a principle ofminimizingimplementationwhilemaximizingfunction.

    Multiplecommands

    Sometimes it isdesirable togivea listofcommandsbeforeexecutinganyof them.Theproblemwith just typingcommandsoneata time is thatas soonasacarriage return istyped,thesystemstartsexecutingthefirstcommand.Therefore,therestofthecommandswouldhavetobetypedwhiletheoutputfromthefirstcommandwasbeingdisplayed.

    Thesolutionistointroduceacommandlineoperatorthatpermitscommandgrouping.

    INPUTdate;lscook

    OUTPUTFriJuly413:28:29EDT2008chap1chap2chap3

    The;operatorisusedtoconcatenateanarbitrarynumberofcommandlines,whichareexecutedinsequence.Thatis,thestringsareinterpretedbythecommandprocessorjustasiftheyweretypedonconsecutivelines.Ofcourseassoonastheshellisprogrammedtorecognizespecialcharacters,suchasasemicolon,somemechanismmustbeprovidedtooverridetheirspecialmeaningifthecharacteroccursinaname.Byconvention,"quotesthe next character on the input line.Thus, ls\;ls is interpreted as the single commandls;ls,notastwodistinctcommands.

    Detachedcommands

    A detached command, batch job or background process, is executed with no terminalinteraction exceptoutput.Theoutput canbedirected to a file, I/Odevice, or theusersdisplay.With the latter option, simultaneous output from detached jobs is intermingledalongwithanyoutputfromtheuserscurrentactivity.AnyinputmustbefromfilesorI/O

  • devices.Chaoswouldresult,forexample,iftwojobstriedtoreadfromthesameterminalatthesametime.Withmoreadvancedsystemsthatsupportterminalwindows,interactionwithdetachedjobsisprovidedbyassigningawindowtoeachjob.

    Theshellsyntaxthatdetachesajobcanbeexpressedasfollows.Toterminateadetachedjob,usethekillidcommandwhereidisthenumberprintedbytheshellafterthecommandlineisexecuted.

    lscook&[1]932

    The user can continue typing and executing commands in the foreground while thebackground, or detached, job executes. Most systems also display some identificationinformation for thedetached job, suchas its job idorwhere itsoutputwill appear.Thefigureillustratesthatusertwohasloggedinandplacedabackgroundjobintoexecution.Thatjobhascreatedthreetasks,orprocesses,toaccomplishitsfunction.

    Wildcardnaming

    Suppose that a user has a file, which has been given a long name for documentationpurposes.Itcanbetedioustotypethelongernameeverytimethefileisreferenced.Thus,a conflict exists between good documentation practice and the programmers desire forbrevity.Aneasysolutionistointroducepatternmatching,orwildcard,symbols.

  • WildCardSymbols

    *matchesanycharacter(s)includingnone?matchesanysinglecharacter[list]matchesanyofthecharactersenclosedby[];c1-c2canbeusedtodenotethesubrangeofcharactersfromc1toc2.

    INPUTandOUTPUT

    cdcooklschap?chap1chap2chap3ls*1chap1lschap[21]chap1chap2lschap[2-34]chap2chap3ls[cd]???1chap1

    Thebracketnotationisusedtospecifyasetofcharacters.Asequenceofcharacterscanbedenotedbya-separator;thus,[a-d]isthesameas[abcd].Notonlydoespatternmatchingsavetypingbutitcanalsobeusedtoanswerquestionsabouttheexistenceorpropertiesofobjectsinthesystem.Forexample,ls*3woulddeterminetheexistenceofanyfileswithanameendingina3.

    InLinux,allwildcardsymbolsareexpandedbytheshell.Forexample,thecommandlschap?startsoutwithtwostringsonthecommandline,butafterwildcardexpansion,itbecomeslschap1chap2chap3.LinuxCprogramsneverseewildcardsymbolsintheirarguments.Theshellexpandsallwild-cardusesintolistsbeforepassingargumentstoapplications.

    I/Oredirection

    Many commands in Linux, in factmany commands inmost operating systems, can becharacterizedasreadingtheirinput,performingatransformation,andproducingastreamof results.Anycommandwith theseproperties iscalledaFILTER.Byconvention, thedefaultassignmentforstandardinputandoutputistheusersterminal.TheshellsupportstheuseoffiltersbyimplementingconventionsthatallowtheusertoredirectthestandardI/Oassignmentstootherprocesses,files,ordevices.Thefollowingnotationisused.

    I/ORedirection

    NotationandMeaning

  • >nameredirectstandardoutputtofilename>>namesameasabove,butappendtotheoutputfile

    If no directory name is specified, the ls command assumes, as a default, the currentdirectory,i.e.cook.ThefollowingexampleillustratestheuseofI/Oredirection.

    SampleCommandandContentoffilex

    ls>xchap1chap2chap3x

    ls>x;ls>>xchap1chap2chap3xchap1chap2chap3x

    Pipes

    Inmanycases,theadoptionofusefulconventionscanleadtofurtherimprovementsinthestructureof a system.This is thecasewithLinuxpipes,whichextend the flexibilityoffilterprograms.

    APIPEcanbeusedtoconnectthestandardoutputofonedetachedcommand,whichmustbeafilter,tothestandardinputofanothercommand.Pipescanbejoinedtoformanarbitrary,linearpipelineofcommands.Eachpipe,asinreallife,isafixed-capacitydatastructurethatisusedasaholdingareaforoutputthathasnotbeenread.Oneprogrammustwritearecordtoapipebeforeanotherprogramcancompleteareadoperation.The|characterisusedtoconnecttwoprocessesbyapipe.

    PipedCommandsandResults

    who|grep14:|sortlists,insortedorder,theuserswhologgedinbetween2(14:00hours)and3PM.ls-l|lprprintsattributesoffilesinthecurrentdirectoryontheprinter

    Withoutpipes,thelastexamplewouldhavetobecodedas

  • ls-l>tempwritetheattributestoatemporaryfilelprtemplistfiletempontheprinterrmtempremovethetemporaryfile.

    Thedisadvantagesofnotusingapipearemoretypingfortheuserandtheuseofafilethatmustthenbedeleted.Thepipeversionalsohasaspeedadvantageinthatallelementsofapipelineexecuteasdetachedcommands.

    ShellProcedures

    Wild-cardnamingconventionsandthepipenotationaredesignedtosavetimeforauser.If certain sequences of commands are used frequently, it is desirable to save thecommands ina file foruseas input to the shell.A fileof commands interpretedby theshell is called aSHELLPROCEDURE. InLinux, a shell file can be executed by justtypingitsname,optionallyfollowedbyanargumentlist.Thus,itistransparenttotheuserwhetheraserviceisimplementedasacommandprogramorashellfile.Asaresult, theLinux command set canbe extended arbitrarily to suit theneedsof the individual user.Shellfilesmustbeset(chmod+x)toexecutableaccesspriortouse.

    Inessence,thepropertiesofshellproceduresaresimilartothepropertiesofproceduresinotherprogramminglanguages.Thereisanotationforparameters,localandglobalvariables,exceptionhandling,assignment,testing,anditeration.Inmanycases,theparametersofshellproceduresbroadenstheirapplicabilityevenfurther.Globalshellvariablespersistacrossmultiplecommandlines.TheyarereferredtoasENVIRONMENTVARIABLES.User-definedglobalenvironmentvariables,whichpersistacrossmultipleterminalsessions,canbedefinedinthehiddenfile.bashrc.Localvariablesarecreated,setanddisappearwitheachshellproceduresexecution.

    AsetofenvironmentvariablesisadatastructurereferredtoasaPROPERTYLIST.Apropertylistisanunorderedsequenceofname/valuepairs.Propertylistsarewidelyusedinsystemsdesignbecauseoftheirflexibilityandtheirextensibility.Forexample,typehotdogintoGoogle,thenlookatthereferencestringthatresults;itisapropertylist!

    CommandLineEnvironmentVariableManipulation

    setlistsallenvironmentvariablesandtheirvaluesecho$PATHdisplaythevalueofanenvironmentvariableexportXX=24createvariableXXandsetittothestring24exportPATH=$PATH:.addcurrentdirectory(.)tothePATH

    Shellprocedurescanhavecommandlineargumentsjustlikeprograms.Ashellprocedureusesapositionnumbertorefertoitsargumentsonthecommandlinefromwhichitwasinvoked.Thus,$1standsforthefirststring(thecommandname)inthecommandline,$2thesecond,$*allstrings,etc.The$prefixisalsousedtorefertopre-definedshellvariables.

    ShellVariablesandtheirInterpretation

  • $#Thenumberofstringsinanargumentlist.$$Thejobidnumberoftheshell.Sincethenumberisunique,thisstringcanbeusedtocreateuniquelynamedtemporaryfiles.$!Thejobnumberusedtoidentifyadetachedcommandexecution.$HOMEThedefaultargument(homedirectory)forthecdcommand,whichchangesthecurrentdirectory.$PATHAlistofdirectoriesthataresearchedtofindthedefinitionforacommandname.

    The $PATH variable is a simple example of how awell-designed shell can be used tocreate a computing environment that is tailored to the individual. The $PATH variableprovidesalistofdirectoriesthataresearchedautomaticallywhenanameisusedthatisnotdefinedinthecurrentdirectory.Typically,thelistincludesauserslogindirectory,thecurrentdirectory,andseveralsystemdirectories.Withoutthisconvention,theuserwouldhavetorememberthenamesofthedirectoriescontainingcommonlyusedcommandsasopposedtojustrememberingthecommandnames.NoviceusersareoftenstumpedwhenusingsystemsinwhichthecurrentdirectoryisnotbuiltintothePATHdefinition.

  • PartsofaCommandThe first command thatwewill examine indetail is theC translator, or compiler. TheLinux name is cc or gcc (G is for Gnu from gnu.org). The Apple OS/X Xcodeprogrammingenvironmentusesgcctodothehardwork.Inthisbook,wedothingsthehardwaysoweusethecommandlinegcccommand.ItisavailableinanyUNIX-derivedsystem: Linux, OS/X, Sun OS. Even Microsofts Visual Studio is just a pretty GUI(graphicaluserinterface)ontopofacommand-linecompiler.Lookinthebindirectoryforcl.

    Ifyoureadtheprevioussectionscarefully,youshouldknowthatifyoutypegccandyougetanotfounderror,theneitheritisnotinstalledoryourPATHenvironmentvariableisnotsetcorrectly.Whatdoesacompilerdo?Whatarethecommand-lineargumentstoacompiler?Howdoesabunchofhumantextbecomeacomputercommand?

    Whatdoesacompilerdo?Youmaynotrememberfromyourearlyschoolingbutthetwomostimportantcomponentsof a language, suchasEnglishorC, are syntaxandsemantics. SYNTAXdefines thelegalorderingofwordsinalanguage;SEMANTICSdefineswhatthewordsmeans.right go bed to now is bad syntax; Go to apple right now. is bad semantics. Thesyntaxofa languageisdefinedbygrammar rules. Rather thangothroughtherules indetail, we provide the reader with examples and themaxim the best way to write acorrectprogramis tostartwithacorrectprogram. The idea is tocopyaprogramfromthebook(ordownloadonefromawebsite),thentomodifytheprogramalittleatatime(referredtoasstep-wiserefinement)untilthedesiredresultisachieved.

    EveryprogramisonesentencederivedfromtheCgrammar.TheCcompilerthenparsestheinputsentencetodetermineitscomponents.Thatactionisalsoreferredtoasasyntaxcheck. Theoutputof the compiler is assembly language instructions (in a .s file) for amachine architecture. A simple operation like 3+4 might generate several machineinstructions. The assembly language instructions are then parsed by an assembler togeneratebinarymachineinstructions,whichcanbedirectlyexecutedbythetargetCPU.The binary instructions, together with a name or symbol table, comprise anOBJECTMODULE.InLinux,thisisa.ofile;inWindowsa.objfile.

    Forlargeprojectswithmanyprogrammers,itwouldbechaosiftheyallwerechangingasingleprogramfile.Therefore, it isadvantageous topartition largeprograms intosmall,manageablepieces.Thepiecescanthenbereassembledintothelargetargetapplication.The pieces that are joined are objectmodules and the program that does the joining iscalled aLINKER. InLinux, the linker command is ld. A linker joins twoormoreobjectmodulestoproduceanoutputobjectmodule,oralibrarymodule.

  • Now you know why an object module has a symbol table. If a program componentreferencessymbols inanothercomponent,howwould the linkerknowwhere theyweredefinedwithoutadirectory?Ifeverysymbolthataprogramusesmustbelinkedwithitprior to execution, the result is called STATICLINKING. If the linking to externalsymbolscanbedeferreduntiltheprogramruns(runtime),theresultiscalledDYNAMICLINKING. Imagine thewasted space if everyoneof the thousandsof applicationsonyourcomputerhadastatically-linkedcopyoftheClibrary.

    The program that turns an object module into an executable image is referred to as aLOADER. The ld program in Linux is both a linker and a loader. The defaultexecutablenameinLinuxisa.out,whichisaremnantoflongagowhenonlyanassemblerexisted.

  • The final step in the compiler discussion is actually the first action taken by the Ccompiler. Every C program is fed through a translator called a macro preprocessor(preprocessor for short) that parses preprocessor statements (denoted by a line startingwitha#),executesthem,andthenoutputstheresultingCprogramwiththepreprocessorstatements removed. AMACRO is a function that takes a string of characters asinputandproducesastringofcharactersasoutput.

    ThepreprocessornotationisusedtodefineCAPIsinfilesreferredtoasHEADERS(witha.hsuffixforCora.hppsuffixforC++).Forexample,theerrno.hheaderfiledefinestheconstantEIO(with thevalue5),which isaccomplishedas followsusingapreprocessormacro. The preprocessor syntax has nothing to do with C syntax; in fact, thepreprocessorsmacrocapabilitiescanbeusedwithanylanguage!

    PreprocessorMacroinerrno.h

    #defineEIO5

    PreprocessorInputFilefoo.c

    #includeEIOEIOEIO

    PreprocessorOutput(gcc-Efoo.c)

    555

    Linuxisveryorganizedinitsdirectorystructure.Systemcommandsarestoredin/usr/bin,header .h files in /usr/include and library files are in /usr/lib. Other operating systemvendorsmimicLinux so the compiler andother toolswill be in a bin directory, headerfilesinanincludedirectoryandlibraryfilesinalibdirectory.

    As it turns out, gcc is a super-program. It combines the preprocessor, parser, codegenerator, assembler, linker and loader all in one command. The options to gcc areprefixed with a - and the arguments like test.c or test.o are just listed on thecommand line. Each separateprogrampart ingcccanbegivencommand-lineoptions.gcccancompileasmany.cprogramsasyoulistonthecommandline.Infact,oneofthenicefeaturesofanycommandinLinuxisthatitwillworkonfiftyargumentsaseasilyasone.

    Hooray!!RUNYOURFIRSTPROGRAM(acircle.cpp)

    1. Be sure to e-mail [email protected] to get a free copy of the exampleprograms.Noregistrationorpersonalinformationisrequested.

    2. Install a version of Microsofts Visual Studio (see dreamspark.com), or AppleXCode.IfyouhaveaLinuxsystem,g++shouldalreadybeinstalled.

    3. Download the SFML version that matches your computer from http://www.sfml-dev.org.SeeLearn/Tutorials/GettingStartedforprojectsetuponeachplatform.The

  • followingdirectionsareforVisualStudio.

    4. Click the Visual Studio icon to start the Integrated DevelopmentEnvironment(IDE).

    5. SelectNewProject tocreatethefirstproject.6. SelecttheC++/Win32,thenConsoleApplication,thenentertheprojectnameacircle,

    thenclickFinishasshownnext.

    7. Theprojectwindowshouldappearasfollows,whichisunfortunatelyaC++program

    thatwillonlyrunonaMicrosoftsystem,whichdefeatstheportabilityadvantageofusinganinternationalstandardlanguage.

  • 8. Rightclickonstdafx.cppandselectRemovefromthemenu,thenDelete.Alsodeletestdafx.handtargetver.h.

    9. Click in the sourcewindow to set the caret, thenCtrl-a to select all the text, thencopy/paste the text in examples/acircle.cpp. The window should now appear asfollows.

    10. Click theBuildmenu item. Themost important entries at this point areCompile(selectedfile)andBuildSolution(compileallfilesandlinktocreateanexecutable).SelectBuildSolution.

    11. Thefirsterrorisunexpectedendoffilewhilelookingforprecompiledheader.Did

  • you forget to add stdafx.h. Select menu item Project/Properties, thenC/C++/PrecompiledHeaders,thenPrecompiledHeader,thenNotUsingPrecompiledHeaders.

    12. Clickmenu itemBuild/BuildSolution. Theerrormessage is Cannotopen includefileSFML/Graphics.hpp:Nosuchfileordirectory.Butinfact,youknowthatthereissuchafilebecauseyoudownloadedandunzippedtheSFMLsystem.TheproblemisthatMSVSwillnotlookformissingitemsautomatically.Itmustbeinstructed.

    13. Click menu item Project/Properties, then selectConfigurationProperties/VC++Directories/IncludeDirectories, then click the drop-downarrow,thenselectEdit.

    14. Theleftmostfoldericoncanbeclickedtoenterapathtoanincludedirectoryfor.h/.hppfiles.

    15. Select the menu item Build/BuildSolution. The error message this time is 17

  • unresolved externals. This is a linker error caused bymissing library files. Thesolutionrequirestwosteps.First,thedependentlibraryfilesmustbelistedaslibraryinputbyeditingProject/Properties.Second,MSVSlinkermustbetoldwheretofindthelibraryfiles.

    16. Select themenu itemBuild/BuildSolution. Hooray! Thebuild succeeds.ClickonLocalWindowsDebuggertoexecutetheprogram.

    17. Unfortunately,theprogramgeneratesaruntimeerrorassoonasitstartsbecausethebinary instruction files that implement the .lib APIs cannot be found. The suffix.dllstandsfordynamic-linklibrary.ClickonBreakthenDebug/StopDebuggingtocleartheerror.

    18. Select the menu item Project/Properties. The working, or current, directory forexecutionneedstobesettotheSFMLbindirectory.SelectBrowseinsteadofEdittonavigatetothebindirectoryslocation.

  • 19. ClickonLocalWindowsDebuggertoexecutetheprogram.Youshouldseeacoolwindowasillustratednext.Notethatifyoupullontheedgeofthewindowtomakeitbiggerorsmaller,thegreencirclescalesproportionally.Cool!

    Howtomakeacommand?Asmentioned earlier, everyC++programcan be a commandbut certain rulesmust befollowed. The programmust read from the keyboard and print to the display. Soundssimple? It is. The programmust handlemultiple command-line arguments (theres anAPItohelp).Theprogramshouldsupportahelpoption-?orhelp.Finally,mostusers create abindirectory for their created commands andadd it to theirPATH.Oncethesestepsarefollowed,anycommandthatyoucreateisbuiltintothesystem.

  • CHAPTERTWOCONSTANTSANDEXPRESSIONS

    IntroductionYoumight think that you understand constants, like 3 or 4, but wait until you see thesyntax and semantics! Once you can handle constants correctly, we move on toexpressions,suchas3+4,thenformulasandthentables.Yes,thereisalotofsyntaxandsemanticsinthoseconceptstoo.RememberthatC++wasdesignedtogiveprogrammersaccesstoanythingthatacomputercouldbetoldtodoinassemblylanguage.Asaresult,C++hasalotofoptionswhendealingwithdata.

  • ConstantsACONSTANT isavalue thatneverchanges. C/C++supports integer (wholenumber)constants, real numbers (fractions),Boolean (true or false), character (letter), and string(zero or more characters). The world of computing is built on these (mostly). Thedifferentdatatypeshaveevolvedoverthedecadesbothtomeethumancomputingneedsand to take advantage of hardware efficiencies. For example, an integer divide 3/4 issignificantly faster than a real divide 3.0/4.0. SinceALUs (remember arithmetic-logicunits)workdifferentlydependingon thedata typeof theiroperands, it is imperativeforC/C++programmerstobespecificabouttheoperationthattheywanttoperform.

    AsecondpropertyofALUsisthatthenumberofbitsinoperandsislimitedinsize.Inthereal world, you can repetitively add one to a number until exhaustion sets in. On acomputerrepeatedadditionislimited.Addingonetothelargestinteger,realnumber,orcharacterisanerror.ThefollowingtableliststhedifferentC/C++datatypes,theirlimitedrangeofvalues,andthesyntaxforeach.

  • RulestoRemember

    1. Allvaluesarebitsinthecomputer.ThedatatypedoesnotbecomerelevantuntilthebitsbecomeoperandsinanALUorFPU

    2. Real numbers are stored in bits, not decimal digits. As a result, there are morerepeating fractions (hence inaccuracies) in binary reals than in decimal e.g.0.610=0.10012. To illustrate further,0.1+0.2yieldsaslightlydifferentanswerfrom0.06+0.24.Also,allrealcalculationsoccurindoubleprecisioninC/C++;therefore,floatshouldonlybeusedwhenanAPIrequiresit.

    3. Nevercomparerealnumbersforequality.SeePoint2.4. Octal(base8)andhexadecimal(base16)constantsareusedwhenprogrammingwith

    specificbitpositions.Octalandhexadecimalareshorthandnotationsforbits,threeat

  • atimeandfouratatime,respectively.5. Real numbers (float/double) have four parts: sign, exponent, sign of themantissa,

    mantissa. TheEsuffix isused for scientificnotationand representspowersof tene.g.2.0E+2equals2000.0E-1equals200.0.Realnumbershaveadecimalpoint.

    6. [email protected]. StringsoccupymultiplebytessohowdoesCknowwherethelastbyteis?Caddsan

    extracharacter\0totheendofeverystringasanend-of-stringmarker.Thusastringofnocharactersoccupiesonebyte(forthemarker).Notethataone-characterstringisdifferentfromachar.

    8. Charactersandstringsbothhavetheproblemofhowtoenternon-printingcharactersoraor.Thefollowingconventionisused.\nWriteacharacter.\rWriteacharacter.\tWriteacharacter.'Writeacharacter."Writeacharacter.\Writeabackslashcharacter.\numWritean8-bitcharacterwhoseASCIIvalueisthe1-,2-,or3-digitoctalnumbernum.

    RUNPROGRAMLISTEDBELOW(bconstant)

    1. ThePrint-FormattedmethodisfromtheClibraryStandardInput/OutputAPI. Thearguments toprintfareastringofformatcodes,whicharedenotedbya%,andanoptional list of values (in the examples: one). Argumentsmust be separated fromeachotherwithacomma(,)justlikealistinEnglish.Theargumentlistasawholemustbeenclosedinparentheses(),whichisnotlikeEnglish.Partofthesemanticsrequire that therebeone formatcode foreveryvalue listed i.e. threevaluesmeansthree formats. The format string can have other content besides the % formats.Theremustbeonevalueforeachformatcode.Eachdatatypehasitsownformatcode.The format codemust alwaysmatch the data type of its correspondingvalue.Moredetailontheformatcodeoptionsislistedinanappendix(click).

    #include

    intmain(intargc,char*argv[],char*envp[]){//intprintf(%d\n,-56);//octalintprintf(%d\n,056);//hexadecimalintprintf(%d\n,0XCAB);//longprintf(%ld\n,123456789L);

  • //longlongprintf(%lld\n,123456789123456789LL);//floatprintf(%g\n,5.6f);//doubleprintf(%lg\n,5.6E+56);//charprintf(%c\n,X);/*char[]orastring*/printf(%s\n,HelloWorld!!);printf(HelloWorld!!\n);return0;}

    2. Totestthebconstant.cppprogramonMSVS,therearetwochoices:1)createanewprojectusingthepreviousinstructionsor2)justaddanewfiletotheacircleproject.Inthesecondoption,rightclickSourceFilesandAddanewfilebconstant.cpp,thencopy/paste the text. If you try to execute the program, the error will be _mainalready defined in acircle.obj. Just change the name main in acircle.cpp tomain2. When theprogramexecutes,aCommandwindowisdisplayed,and thenquickly disappears. Select themenu itemDebug/StartWithoutDebugging to pauseexecutionsothattheoutputcanbeexamined.

    3. Modifyeachlinetotrydifferentconstants.Usingstep-wiserefinement,onlymodifyone line at a time. If you get a compilation error, revert to the last program thatworkedandtryagain.Remembercopycodethatworks!

    4. OUTPUT-56

  • 4632431234567891234567891234567895.65.6e+56XHelloWorld!!HelloWorld!!

    Abigthemeofthisbookistolearnbydoing.Nooneeverlearnedalanguagebyreadingabout it. The first rule in learning to program is called the hello world step. It isconsidered a significant accomplishment for a novice if they can create a program thatprints thestringhelloworld. Basically, thatmeans theyknowa lotofwhathasbeendiscussed so far. Other than thatknowledge, there is a secondary advantage.Knowinghowtoprintmeansthatprintingcanbeusedtoexploretherestofaprogramminglanguage. Ifyoudonotunderstandsomething,writea tiny testprogramthatprints theresult.WhenusinganewAPIforthefirsttime,alwayswriteatinyprogramtomakesurethatyouunderstanditsfunctionsbeforeusingtheAPIinalargerprogram.Theexampleaboveprintsoneofeachtypeofconstant.

    AllCprogramsreallystartexecutionintheClibrary.If that isso,howthendoestheClibrary knowwhere your program starts? The answer is that the objectmodule for thelibraryhasasymbolreferencetothenamemain.

  • LineSyntaxInC,asequenceofblanksortabsisnotsignificantexceptinstrings.Thusintmainisasvalidasintmain;however,intmainisillegal.Ifyoushouldmakeatypoinyourprogram, theCcompilerprintsout a listof errormessages,usuallywith linenumbers.Mosteditorswillupdateadisplayofthelinenumberasyoumovethecaret.

    Stringsobviouslyrequiresomekindofmarker(suchas)sothat theparsercantell thedifference betweenC reservedwords (if return dowhile etc.) and a users strings (ifreturn etc.). In a similar fashion, there exist markers to allow programmers to addexplanatory,Englishcommentstotheircodeforthebenefitofothers.SomeCcodehasbeeninuseforoverfiftyyears!Therearetwocommentsyntaxdefinitions//and/**/.Inthefirst//,allcharactersfromthe//tothenextend-of-linecharacterareignored.Thesecondconvention/**/enclosesthetextthatcomprisesthecomment(notethat*/cannotbeinacomment).Bothcommentconventionswereusedinthebconstantprogram.

  • ExpressionsTheClanguagehasarichsetofoperators. Unlikethedatatypeswheretherearemanydifferent formsofan integer,CoperatorsarePOLYMORPHIC,whichmeans that oneoperator(like+or-)workswithanyofthedatatypes.Therearethreeoperators(*/%)that have a different interpretation than the traditional operators used in math books.Asterisk (*) is the Cmultiplication operator. Slash (/) is the division operator. Unlikehuman arithmetic in which 34 equals 0.75, in computer integer arithmetic, integerarithmeticonlyresultsinintegerssotheremainderisdiscarded.Thequotientof3/4thenis zero. In computer real-number arithmetic, the result would be as expected. Thepercentage(%)operatorisusedformodulocalculations,butonlyonintegers;thatis,theintegerremainderondivision(e.g.3%4=3,13%4=1).

    Thefollowingprogramusesprintftotesteachofthearithmeticoperators.Inthelasttwoexamples,notethattheproductoftwovalidfloatsistheillegalinf(infinitymeaningtoobig)value.However,theproductofadoubleandafloatiscarriedoutindoubleprecision,producingthecorrectresult.

    RUNPROGRAMLISTEDBELOW(coperator)

    1. Copyandpastebelow.

    #include

    intmain(intargc,char*argv[],char*envp[]){//intprintf(3+4%d\n,3+4);printf(3-4%d\n,3-4);printf(3*4%d\n,3*4);printf(3/4%d\n,3/4);printf(3%%4%d\n,3%4);printf(3+4*6%d\n,3+4*6);printf((3+4)*6%d\n,(3+4)*6);//longprintf(9999L*9999L%ld\n,9999L*9999L);//longlongprintf(999999LL*999999LL%lld\n,999999LL*999999LL);//doubleprintf(5.6+3.2%lg\n,5.6+3.2);printf(5.6-3.2%lg\n,5.6-3.2);printf(5.6*3.2%lg\n,5.6*3.2);printf(5.6/3.2%lg\n,5.6/3.2);//floatprintf(5.6E+20f*0.234E+25f%lg\n,5.6E+20f*0.234E+25f);

  • printf(5.6E+20*0.234E+25f%lg\n,5.6E+20*0.234E+25f);return0;}

    2. Compileandexecutetheprogram.3. Modifyeach line to trydifferent constants in theexpressions. Tryusingoctal and

    hexadecimalconstants.Usingstep-wiserefinement,onlymodifyonelineatatime.Ifyougetacompilationerror,reverttothelastprogramthatworkedandtryagain.Remembercopycodethatworks!Trychangingdifferentcharactersintheprogramtobecomefamiliarwithsomeoftheerrormessagesthatthecompilergenerates.

    4. OUTPUT3+473-4-13*4123/403%433+4*627(3+4)*6429999L*9999L99980001999999LL*999999LL9999980000015.6+3.28.85.6-3.22.45.6*3.217.925.6/3.21.755.6E+20f*0.234E+25finf5.6E+20*0.234E+25f1.3104e+45

    MODIFYPROGRAMONE(dcolorshape)

    1. Hopefully,thereaderhasmasteredprintf,constantsandexpressions.However,thereisnotabigmarketforthoseprograms.Ontheotherhand,youshouldhavelearnedenoughaboutsyntaxtomodifyexistingcode.

    2. Copy the following program and verify that it executes correctly. Change thewindowsizeaswellastheshapesizes,positions,colors,andoutlines.RightclickonthewordColorintheIDEseditwindow,thenselectGotodeclarationtoseealistofcolornames.

    3. Notice thatunlike theCartesiancoordinatesystem, the intersectionof theXandYaxes(theORIGIN0,0)isnotlocatedinthemiddleofawindow,butintheupper-leftcorner.Further,thepositiveYaxisisdown,notup.

    4. Be aware that when drawing shapes in SFML, the outline width ADDS to thedimensions. For example, a circle with a radius of 10 and an outline width of 4wouldactuallyhavearadiusof14andadiameterof28.

    CartesianXYAxes

  • ScreenXYAxes

    #include#include

    intmain(intargc,char*argv[]){ sf::RenderWindowwindow(sf::VideoMode(640, 480), SFMLworks!); //640-

  • width480heightsf::CircleShapecircle(50.f);//50-circleradiussf::RectangleShaperect;sf::Vector2fsize(8,480-32);//8-width448-heightcircle.setFillColor(sf::Color::Blue);circle.setOutlineColor(sf::Color::Red);circle.setOutlineThickness(4);//4-linewidthcircle.setPosition(100,150);//x=100y=150rect.setFillColor(sf::Color::Green);rect.setOutlineColor(sf::Color::Yellow);rect.setOutlineThickness(4);rect.setPosition(320,16);rect.setSize(size);

    while(window.isOpen()){sf::Eventevent;while(window.pollEvent(event)){if(event.type==sf::Event::Closed)window.close();}window.clear();window.draw(circle);window.draw(rect);window.display();}return0;}

    5. Compile,modifyandexecutetheprogram.

  • Informattingaprogram,itisrecommendedtoplaceaspacebeforeandaftereachoperatortomaketheprogramclearertoyou,andtoothers.

    Whatdoes3+4*6evaluate to? Is it3+4=7 then7*6or is it4*6=24then3+24?Theansweristhelatterandthereasonistermedoperatorprecedence,whichbasicallymeansthatinparsinganexpressionfromlefttoright,higherprecedenceoperatorsareexecutedfirst.Theprecedenceofanoperatorisdefinedbythegrammarrulesofalanguage,whichcanbetrickytoremember.Theleft-to-rightpartalsofoolspeople.Werecommendthatallexpressionsbefullyparenthesized(). Thus,with(3+4)*6or3+(4*6) therearenomistakes.

    OPERATORPRECEDENCEandASSOCIATIVITY

    Expressionsareevaluatedfromlefttoright,oftwoadjacentoperators,theonewithhigherprecedenceisevaluatedfirst.Iftheoperatorshaveequalprecedence,associativitydeterminesleft-to-rightorright-to-leftorder.Binaryaddition+(a+b+c)isleftassociative;bisaddedtoafirst.Unarynegation-isrightassociative(3);therightmost-isevaluatedfirst.

  • 3+5+6*7==(3+5)+(6*7)

    3+5*6-7==(3+(5*6))-7

    6*8*9==(6*8)*9

    7+3*6/2-1==(7+((3*6)/2))-1

  • FormulasandTablesIn this section, we investigate the evaluation of formulas in C. Typically, a real-worldformula,suchasCentigrade=5/9(Fahrenheit-32),mustbetranslatedtoaCexpression.Cisavaluabletoolforcomputingtablesofarangeofinputvaluesforaformula.Usingacomputer program to evaluate a formula, or to generate a table, can be faster and lesserror-prone than performing the calculation manually, or even faster than using acalculator.

    Typically,foratable,theinput(termedINDEPENDENTVARIABLES)islistedontheleftandtheoutput (termedDEPENDENTVARIABLES) is listedon the right.Consider the followingtableofsquaresandcubesforthevaluesof1to5oftheindependentvariablex(usuallytheindependentvariableisgivenaname).First,theprogramprintsoutaheadingforthetable.How?Theprintfstatement isused towrite text; therefore, it isused tooutput theheading.

    #includeintmain(void){//outputtableheadingprintf(xx^2x^3\n);

    Sincemoderncomputersaresofastandsinceweadvocatestep-wiserefinement,itisoftenless error prone to modify a program just a few lines at a time, then to compile andexecute. The values in a table are computed by typing expressions. There is noexponentiationoperatorinCsothesquaresandcubesarecalculatedusingmultiplication.

    //outputtablevaluesprintf(%d%d%d\n,1,(1*1),(1*1*1));printf(%d%d%d\n,2,(2*2),(2*2*2));printf(%d%d%d\n,3,(3*3),(3*3*3));printf(%d%d%d\n,4,(4*4),(4*4*4));printf(%d%d%d\n,5,(5*5),(5*5*5));}OUTPUTxx^2x^3111248392741664525125

    Noticethattheoutputisallsmashedtogether.Theprogramworkedperfectlytooutputthetable but the program is not correct! Why? The program does not satisfy the newrequirement introduced by tabular output. That is, the program must 1) evaluate theformula correctly and 2) generate output conforming towhat humans expect a table tolooklike.

    Amodifiedprogramthatuses tabcharacterssatisfiesbothrequirements.Anotherchoicewouldhavebeen toput ablankbetweeneach format item.Try it.Why is a tabbetter?

  • Alsonotice that typing theTABkeybetween the format codeswouldalso lead topoorresults, aswell as a programwith invisibleparts! Finally, theoutput is left-justified ineachcolumn.Whatifwewanteditcentered?

    Square/CubeProgram(esquares)

    #includeintmain(void){//outputtableheadingprintf(x\tx^2\tx^3\n);//outputtablevaluesprintf(%d\t%d\t%d\n,1,(1*1),(1*1*1));printf(%d\t%d\t%d\n,2,(2*2),(2*2*2));printf(%d\t%d\t%d\n,3,(3*3),(3*3*3));printf(%d\t%d\t%d\n,4,(4*4),(4*4*4));printf(%d\t%d\t%d\n,5,(5*5),(5*5*5));return0;}OUTPUTxx^2x^3111248392741664525125

    TablesWithDecimalPointsThe advantage of using real numbers is that you can calculate tables with non-integerformulas, such as a centigrade toFahrenheit conversion table. First, do notmix integerconstants and double constants; that is, do not write 3.0+5, but rather either 3+5 or3.0+5.0.This is a semantic rule.Violationscan result in runtimeerrorsorcompile-timeerror messages. The following program/table illustrates the Centigrade to Fahrenheitcalculation.Noticethat1.8isthesameas14/5,whichisthesameas9/5.F=9/5C+32

    ProgrammingHint:Whencalculatingarealnumbertable,makesurethateverynumberhasadecimalpoint.Whencalculatinganintegertablemakesurethatnoneofthenumbershavedecimalpoints.

    CentigradetoFahrenheit(fcents)

    #includeintmain(void){//convertCtoFprintf(C\tF\n);printf(%lg\t%lg\n,11.0,(1.8*11.0+32.0));printf(%lg\t%lg\n,21.0,(1.8*21.0+32.0));printf(%lg\t%lg\n,31.0,(1.8*31.0+32.0));printf(%lg\t%lg\n,41.0,(1.8*41.0+32.0));printf(%lg\t%lg\n,51.0,(1.8*51.0+32.0));return0;

  • }OUTPUTCF1151.82169.83187.841105.851123.8

    BigTables

    Printingatablewith20,30,or50rowscouldbequitealotoftypingatonelineofcodepertablerow.ByusingtheCforstatement,theamountoftypingcanbereducedtooneline.The syntax/semantics of the exampleswill be covered in a later chapter. For now,thinkofthefollowingexamplesasatemplate,orpattern,thatyoucanmodifytoprintatableforanyformula.

    Centigrade>FahrenheitProgram(gtable)(Justchangetheformulatoproduceadifferenttable)

    #includeintmain(void){doublex,stop,increment;//stopmustbebiggerthanstart//change11.0tothedesiredstartvaluex=11.0;//change51.0tothestoppingpointstop=51.0;//change10.0tothetableincrementincrement=10.0;//outputtableheadingprintf(C\tF\n);for(;x

  • 2. ModifytheprogramtoconvertFahrenheittoCentigrade.Thehumanformulais(F-32)*(5/9).

    3. Noticethatwhatevercodeisintheforloopisrepeatedanumberoftimes.ItwouldbecooltocopythegoodpartsofthisexamplearoundthecodetodrawmultiplecirclesatdifferentpositionsinProgram1.

    MultipleCircles(hcircles)

    #include

    intmain(intargc,char*argv[]){sf::RenderWindowwindow(sf::VideoMode(600,600),SFMLworks!);sf::CircleShapeshape(10.f);intx,stop,increment;//stopmustbebiggerthanstart//change600tothestoppingpointstop=600;//change20tothetableincrementincrement=20;shape.setFillColor(sf::Color::Green);

    while(window.isOpen()){sf::Eventevent;while(window.pollEvent(event)){if(event.type==sf::Event::Closed)window.close();}window.clear();//change10tothedesiredstartvalue//mustbereseteachtimethatthewindowisdrawnx=10;for(;x

  • CHAPTERTHREESTATEMENTS

    IntroductionThereaderhasprobablyobservedthatthereisalotmoretoC/C++syntaxthanwhatwehavediscussedsofar.InthisChapter,wecovervariables(notconstants),variableinput(readingfromthekeyboard),andstatements,suchasassignment(copyingavalueintoavariable),conditionaltestingandlooping.Withthisadditionalinformation,moreshouldbecomeclearabouttheprogrammingexamplesdiscussedsofar.

    Beginnersalwayshaveproblemsrememberingsyntaxrules.GoogleorYahooCorC++quickreference,printthedocument,andkeepithandywhencoding.

  • VariablesAvariableinallprogramminglanguagesisaname-value(s)pair.Referencinganameisthesameasreferencingitsvalue(s).Likeanyothercomponentofacomputerlanguage,nameshavesyntaxrules.Forexample,ben-gurionmightbeavalidhumanname,butinC/C++,theminussign(-)indicatessubtraction.Therefore,minussignsandotherspecialsymbolscannotbeusedinnames.ACnamemustbeginwithanunderline(_)oraletter(A-Zora-z).AC/C++namecancontainanylettersordigitsorunderlines.

    NameExamples

    _hellogood_byeY567

    Sinceanamerepresentsavalue,thereisthequestionofthedatatypeofthevalue.Insomecomputerlanguages,namescanstandforavalueofanydatatype.InC/C++,thebindingofanametoadatatypeoccurswhenyouwriteaprogram.Thisisreferredtoasstaticbindingbecauseitoccursbeforeaprogramisexecuted.Actions,suchasdatatypebinding,thatoccuratruntimearedefinedasdynamic.Forexample,staticlinkingoccurswhenyouusealinkertojoinobjectmodules.Dynamiclinkingoccurswhenthemodulesreferencedbyaprogramarelinkedatruntime.InWindows,thesuffix.dllisanacronymforDynamicLinkLibrary.

    DeclarationsThetermDECLARATIONisusedfortheC/C++statementthatdefinesanewvariablename(oranidentifierincomputer-speak).Namesmustbedeclaredbeforeuse(generally).Namescannotbedeclaredmorethanonce,exceptincircumstancestobedescribedlater.DeclarationstatementsmustoccurbeforeotherstatementsinC,butnotinC++.Thesyntaxruleisthatadeclarationstatementmustbeginwithatypename(shortcharintdoubleetc.)followedbyacomma-separatedlistofnamesendingwithasemicolon(;).Eachnamecanoptionallybefollowedbyanequalsign(=)andaninitialvalue,whichcanbeanexpressionthatconsistsonlyofconstants.Someexamplesfollow.

    VariableDeclarationStatements(iconst)

    #include

    intmain(void){intx,y=3+4,Z;longL=8765L;constdoublePI=3.14,E=2.78;charch=M;printf(y=%dL=%ldPI=%lgch=%c\n,y,L,PI,ch);return0;}OUTPUTy=7L=8765PI=3.14ch=M

  • 1. Copy,compileandexecutetheprogramtoverifytheoutput.Trychangingthevalueoftheinitialvaluestodifferentconstantsandexpressions.

    2. Copythelinebeginningwithprintf.Insertitafterthe{butbeforethedeclarations.Thecompilershouldprintanundeclaredidentifiererrormessageforeachname,eventhoughtheyareobviouslydeclared.Remembertheruledeclaredbeforeotherstatements.Eventhesimplestmisspellingortheomissionofadeclarationcanleadtoerrormessages.

    3. Thekeywordconstcanbeusedasadeclarationprefixtoindicatethatthename-valuepairingispermanentandunchangeable.Namedconstantsareoftendeclaredinall-capitalletters.

    Inlargesoftwarehouses,itisnotuncommonfortherules-of-the-housetoincludearequirementforHungariannaming(afterCharlesSimonyioneofthearchitectsofMicrosoftWindows).Theideaisquitesimple.Eachvariableisgivenaprefixtoindicateitstype(iforinteger,dfordouble,cforcharacter,sforstringetc.).Thepurposeistofacilitateprogrammaintenancebymakingeachuseofanameobvious.Rememberthatdeclarationsoccurpossiblymanypagesofcodebeforetheirvariablesareused.Hungariannotationmakesitunnecessarytoreferbacktodefinitions.InMSVS,right-clickavariablethenselectPeekdefinition.

    ChangingavariableWewouldntcallthemvariablesiftherewerenotsomewaytochangethem.Thetwochoicesaretosetanewvaluefrominputorfromassignment(copyingfromaconstant,expressionoranothervariable).Changingavariableviainputcanoccurbyfilling-in-the-blankinaGUIenvironment,bytypingfromakeyboardorbyreadingfromafile.Thefollowingexampleillustratesreadingvaluesfromthekeyboardusingthestdio.hAPImethodscanf.Thescanfmethodusesthesameformatsasprintf;however,thesyntaxrequiresanampersand(&)beforeeachvariable.

    OneoftheproblemswithreadingfromthekeyboardinsteadofaGUIenvironmentishowdoestheuserknowwhenorwhattotype?.Remembertheshellinterpreterbeginseachlineofuserinputwithaprompt.InC/C++programming,prompt-charactersaretheresponsibilityoftheprogrammer.Ifyoudonotoutputauser-friendlyprompt,theusermaybeconfused,orworse,maybestuckwaitingforthecomputertodosomething.

    TheexampleusesthescanfmethodtoreadaCentigradenumberandconvertittoFahrenheit.Noticethatthepromptdoesnothavea\n!Thisallowstheusertotypeonthesamelineastheprompt.

    CtoFWithUserInput(jread)

    #includeintmain(void){//convertCtoFdoubledCentigrade=0;

  • printf(enteraCentigradenumber(Enter):);scanf(%lg,&dCentigrade);//willneedtobechangedtoscanf_sprintf(C\tF\n);printf(%lg\t%lg\n,dCentigrade,(1.8*dCentigrade+32.0));return0;}INPUT/OUTPUTenteraCentigradenumber(Enter):67CF67152.6

    1. Theprogramgeneratesanunexpectederrorscanf:This functionmaybeunsafe.GoogleorYahoobufferoverflowattack.TheoriginalClibrarydoesnocheckingforerrors. Malicioususerscanexploit thedeficiency tooverwritecritical areasofmemory. As a result, the C library has been extended with security-checkingversions of the standard functions (denoted by _s). Thus, printf_s is the secureversionof printf and scanf_s is the secure versionof scanf. The remainder of thebookusessecurenaming.

    2. Noticethat thedCentigradenameinscanfisprecededbyan&. Tryomittingthe&.Chaosensues.ItlockedupMSVSwhenItriedit.Thereasonisthatthe&causesthememorylocationofdCentigradetobemodified.Withoutthe&,thecurrentvalueofdCentigradeisusedasitsmemoryaddress!!

    AssignmentStatement

    Theassignmentstatementcopiesthevalueofaconstant,expression,oranothervariableintoatargetvariable.Thetargetisreferredtoastheleft-handside(LHS)oftheassignment;thevalueastheright-handside(RHS).ThedatatypeoftheRHSshouldbethesameastheLHS.NoneoftheoperandsontheRHSareaffectedbytheassignment;however,anyoldvaluefortheLHSistotallyreplaced.

    Forhistoricalreasons,C/C++referstoanexpressionthatcanoccurontheLHSofanassignmentasanLVALUE.Thefollowingexampleillustratesthesyntaxandthesemanticsofanassignmentstatement.Thegtable.cppusedthreeassignmentstatementstodefinethetablesparameters.

    AssignmentStatementSyntax(kassign)

    variable=variable;variable=constant;variable=expression;

    #includeintmain(void){intx,y=3+4,Z;longL=8765L;doublePI=3.14,E=2.78;

  • charch=M;

    x=y;L=8765L;PI=PI*E;ch=M;printf_s(x=%dL=%ldPI=%lgch=%c\n,x,L,PI,ch);return0;}OUTPUTx=7L=8765PI=8.7292ch=M

    TheC-to-Fprogramaswritteniscute,butisnotLinux-tough!ThereasonisthatrealLinuxcommandsdonotprintfancyprompts;theirinputcomesfromthecommandline.Also,Linuxcommandsdonotprintalotofnoisewords;theyjustreadinputandproduceoutput.Intheshelldiscussionearlier,itwasmentionedthatthecommand-linearguments(argv)andtheenvironment(shell)variables(envp)arecommunicatedbytheshelltoeveryC/C++program(henceeverycommand).Inthefollowingexample,theC-to-FprogramismodifiedtosetdCentigradefromthecommandline.Rememberthatallcommandlineargumentsarestrings.Rememberthatstringsareadifferentdatatypefromdoubles.Therefore,anAPImustbesoughtthathasamethodtoconvertastringnumber3.4toadouble3.4.Modernprogrammingisaboutnotprogramming,findtherightexistingAPItodotheworkforyou!Thestdlib.hAPIhasamethodatof(itispoorlynamed!)thatconvertsastringtoadouble.Nowwejustneedtoknowhowtoaccessthepartsofargv.

    CommandLineArgumentslsalphabetacarladoggammahupionjule

    argv[0]/bin/lsargv[1]alphaargv[2]betaargv[3]carla..

    CtoFCommandLine(lcommand)

    #include#includeintmain(intargc,char*argv[],char*envp[]){//convertCtoFdoubledCentigrade;

    dCentigrade=atof(argv[1]);printf_s(%g\n,(1.8*dCentigrade+32.0));return0;}INPUT/OUTPUTlcommand0

  • 32

    1. OnLinux,tochangetheexecutablenamefroma.outtolcommand,usethe-onamecompileroptioni.e.g++-olcommandlcommand.cpp.

    2. Copy, compile, and execute the program (./lcommand) from a shell. Try differentinputs.

    3. To test the program inMSVS, the command line argumentsmust be set using thedebuggerdialog.SelectmenuitemProject/Properties.

    4. lcommandisstillnotgoodenough.Itdoesnothandlemultipleargumentsonthecommandline.

    5. Weintroduceanothercodepattern,whichisexplainedlater.ThepatternsetsavariablesTargettoeachcommandlineargumentinturn.Trythisversion.Ithandlesanynumberofarguments,includingzero.

    6. Rememberthatifaprogramcompilesbutdoesnotexecutecorrectly,placeaprintfaftereverylinetoseewhatishappening.

    CtoFArgVPattern(mcommand)

    #include#include

    intmain(intargc,char*argv[],char*envp[]){//convertCtoFchar*sTarget;intiTarget=1;doubledCentigrade;

    for(;argc>1;argc=argc-1,iTarget=iTarget+1){sTarget=argv[iTarget];

    dCentigrade=atof(sTarget);printf_s(%g\n,(1.8*dCentigrade+32.0));

    }/*for*/

  • return0;}INPUT/OUTPUTmcommand010050-83221212217.6

    Imadeastupidmistake(welcometoprogramming)inthemcommandprogram.Iforgotthe#include.Thisgeneratednocompilerorlinkererrors!However,foraninputof3.5thedCentigradevaluewassetto4.23011e+006,not3.5asitshouldhavebeen(ofcourseFwaswrongtoo).Theerrorprovidesagoodlesson.

    Rememberhowthelinkercantaketwocompiledprogrampiecesandmakethemone.WellCassumesthatifitseesanAPIreference,suchasatof(),thatitdoesnotunderstand,itmustbeinanotherprogrampart.ButhowdidtheCcompilerknowthatatoftookastringargument?TheansweristhatCdidnotknow!Itmadeanassumption(int),whichwaswrong.Furtherthelinkerdoesnotdotypechecking.Sothenameatofreferencedinctof.cwasfoundintheClibrarybutthetherewasnowaytodetectanargumentmismatch.Thereforeatruntime,garbagewaspassedintotheatoffunctionandgarbage4.23011e+006camebackout.ReferencestoundeclaredAPIscancauseyourprogramtofail.

  • ConditionalStatementAconditionisanothernameforaBooleanexpression(afterGeorgeBoole)andanaction.Everykidhasheardthefollowingcondition:Ifyoudontpickupyourroomthisinstant,wellIdontknowwhat!.TheBooleanconditioniseitherthattheroomwillbepickeduporitwont.Thus,beforetalkingabouttheactionpartoftheconditionalstatement,weneedtodiscussBooleanexpressions.

    BooleanexpressionsBooleanexpressionscomeintwoforms:comparisonsandconnectors.Acomparisoncanbeforequality(==hastobedifferentfromassignment=),non-equality(!=),greaterthan(>),lessthan(=)andlessthanorequal(

  • NOT(~),BooleanNOT(!),short-circuitBooleanAND(&&)andshort-circuitBooleanOR(||).Connectorsrequireabitofexplanation.AlogicaloperatorappliesitsBooleanoperationtoeverysinglebitinitsoperands.Iftheoperandsareshorts,all16bitsareevaluated;iftheoperandsareints,all32bits.Ontheotherhand,theBooleanconnectorstreateachentireoperandaseitherfalse(equaltozero)ortrue(notzero).Forexample,0x123&0xEDCequals0xFFFbut0x123&&0xEDCequals1(ortrue).ThelogicalconnectorscorrespondtohardwareALUoperations;theBooleanconnectorscorrespondtohumanBooleanarithmetic.

    Short-circuitevaluation

    RememberthatCwasdesignedforhigh-efficiency.Inprogramming,itisoftenthecasethattwocomparisonsarejoinedbyanAND(bothtrue)orOR(eithertrue).ComputergurusrealizedthatifthefirstANDoperandisfalse,theexpressioncannotbetrue(false&&anythingequalsfalse).Similarly,ifthefirstORoperandistrue,theexpressionmustbetrue(true||anythingequalstrue).TheresultingAhaistermedSHORT-CIRCUITEVALUATION.Theoptimizationistoskiptheevaluationofthesecondoperandifthefirstoperandisfalse(&&)ortrue(||).Forlogicalconnectors(&|^),bothoperandsarealwaysevaluated.

    Astheexamplesbelowillustrate,short-circuitANDevaluationisoftenrequiredinsituationsinwhichthefailureofthefirsttestwouldgenerateanerrorifthesecondexpressionwereevaluated.Theexamplechecksavariableforzero,thenskipsadivision

  • ifithasthatvalue.

    Short-CircuitExamples

    x=((a!=0)&&((x/a)>9))//ifaequals0,the2ndexpressionisnotevaluated

    x=((a!=0)&((x/a)>9))//ifa==0,thestatementgeneratesaruntimeerrorbecausex/0isundefined

    AssertmacroManyAPImethodsnotonlyperformanactionbuttheyalsoreturnavaluethatcommunicatesinformationtotheuseraboutwhathappenedduringtheaction.Forexample,printf_sandscanf_sbothreturnacountofthenumberofitemsformatted.Forscanf_s,thecountisparticularlyuseful(withaconditionaltest)todetermineiftheusertypedtheend-of-inputcharactersequence.NotethathittingtheEnterkeydoesnotterminateinput.

    TheassertmacroinAPItakesaBooleanexpressionasanargument.Ifitistrue,nothinghappens.Iftheexpressionevaluatestofalse,theassertstopstheprogramandprintsthetextofthefailedBooleanexpression,filenameandthelinenumberatthepointoffailure.Theassertmacroisusedinsituationswheretheprogrammersneedstovalidateaprogramstatethatshouldbetrue.Foranoviceprogrammer,youcouldputanassertoneveryotherlineofcodetoverifythataprogramwasbehavingasexpected.Assertsprovideinformationforaprogrammer.

    ReadANumberfrom1to10(nassert)Assertonnoinputorbadnumber

    #include#includeintmain(void){intx,n;printf_s(typea#from1to10>);n=scanf_s(%d,&x);assert(n==1);assert((x>=1)&&(x6thankyouEND-OF-INPUT(Windows)typea#from1to10>^ZAssertionfailed:n==1,filefoo.c,line7BADINPUT

  • typea#from1to10>11Assertionfailed:(x>=1)&&(x
  • IFstatementTheconditional,orifstatementisverymuchlikeEnglish,exceptforthesyntax.Therearethreeforms:simple,alternativeandmultiple.ThesimpleformjustchecksaBooleanexpression;ifitistrue,acollectionofstatementsisexecuted;iffalse,thestatementsareskipped.Thealternativeformincludesanelseandanotherlistofstatements.TheelseclauseisexecutediftheBooleanexpressionisfalse.Finally,themultipleformsupportsanynumberoftestconditions,forexample,anIRSincometaxtable.Theelseifcomponentcanberepeatedasmanytimesasnecessary.TheBooleanexpressionsinthemultipleformshouldbecomplete;thatis,if(x>5)isinonepart,(x=22)(x>12).Presumably,theintentistopartitionthetestspaceintonumberslessthanorequaltoone,betweentwoandseven,betweeneightandtwelve,thirteenandtwenty-one,andgreaterthanorequaltwenty-two.Greater-thantestsmustbeorderedfromhightolow(221271)tobecorrect.Less-thantestsmustbeorderedfromlowtohigh.

    Justasparentheses()groupexpressions,thebracesymbols{}areusedtogroupalistofstatements.Indentthestatementsina{}group.

    Theexampleforifstatementsstartswithaproblemstatement,thenusesstep-wiserefinementtodevelopasolution.TheproblemistomodifyProgram1toreadthreesetsofX-Yvalues,verifythattheydescribearighttriangle,thendrawthetriangle.

    IFStatementExamples

    Simpleif(BooleanExpression){//anylistofstatements,notdeclarations}/*if*/

    Alternativeif(BooleanExpression){//anylistofstatements,notdeclarations}else{//anylistofstatements,notdeclarations}/*if*/

    Multipleif(BooleanExpression){//anylistofstatements,notdeclarations}elseif(Booleanexpression){//anylistofstatements,notdeclarations}elseif(true){//anylistofstatements,notdeclarations

  • }/*if*/

    PROBLEMSTATEMENT

    1. ModifyProgram1toreadthreesetsofX-Yvalues,whichrepresentthecornersofatriangle.

    2. Verifythattheydescribearighttriangle.

    STEP-WISEREFINEMENT

    1. ThefirststepReadthreesetsofintegerX-Yvaluesrequires3x2orsixvariables.Dontworryaboutthereadingpart.Justdeclarethesixvariableswithinitialvalues.Aprogramthatworkswithconstantsisasimplerfirststepthanaprogramthatreadsitsinput.Inprogramming,alwaystrytosimplifyrequirementthenusestep-wiserefinementtobuilduptothegoal.

    2. Now,howdoyoucheckthatthreepointsarearighttriangle.Weuseifstatementsofcourse,buthow?Thehowpartisinthedomainofalgorithms.Therearemanycoursesbeyondthisonethatteachalgorithms.Googlerighttriangletest.ThetophitshouldexplainwhatarighttriangleisandindicatethatthePythagoreantheoremcanbeusedtotestfortherightproperty.Thetheoremstatesthatthesumofthesquaresofthelengthofeachoftherightanglesidesmustequalthesquareofthelengthofthehypotenuse(the3rdside).

    3. Asoftenhappens inprogramming,wenowhaveasub-problem.Given twopoints,howdoyoucalculate the lengthof the connecting line?Google distancebetweentwopoints.Noticethatthesquarerootdisappearswhenthedistanceissquared.

  • 4. Writeadistancecheckprogram.Neverdevelopnewnon-trivialcodeinthemiddleofalargerprogram!Alwayswriteaseparatelittleprogramfordevelopment,thencopythenowcorrectcodeintothelargerprogram.ALWAYSMAKEUPTESTDATABEFOREWRITINGANYCODE!.Assumethattheleft-bottomcornerofthePythagoreantriangleinthepictureislocatedat0,0.Theothertwopointswouldbeat3,0and0,4.Thedistance-squaredcalculationshouldresultinvaluesof9,16,25.

    #include

    intmain(void){intx1=0,y1=0,x2=3,y2=0,x3=0,y3=4;intd12Sq=(x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);intd23Sq=(x2-x3)*(x2-x3)+(y2-y3)*(y2-y3);intd13Sq=(x1-x3)*(x1-x3)+(y1-y3)*(y1-y3);printf_s(%d%d%d\n,d12Sq,d23Sq,d13Sq);return0;}

    5. Thenextrefinementistocomparethesumoftheright-anglesidedistancessquaredtothesquareofthehypotenuse.Thereisaproblem!Thelocationoftherightangleisunknownwhen the input is any threepoints. The solution is to check eachof thethreecorners.IfthePythagoreantheoremholdsforanycorner,theinputdescribesarighttrianglesincetherecanonlybeonerightangle.

    6. Construct coordinates to test each of the three cases. Add a check that the threepointsdo,infact,describeatriangle.

    intx1=10,y1=10,x2=13,y2=10,x3=10,y3=15;intd12Sq=(x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);intd23Sq=(x2-x3)*(x2-x3)+(y2-y3)*(y2-y3);intd13Sq=(x1-x3)*(x1-x3)+(y1-y3)*(y1-y3);printf_s(%d%d%d\n,d12Sq,d23Sq,d13Sq);

    if(d12Sq+d23Sq==d13Sq){printf_s(righttriangle);}if(d13Sq+d23Sq==d12Sq){printf_s(righttriangle);}if(d12Sq+d13Sq==d23Sq){

  • printf_s(righttriangle);}

    Nowmodify theprogram (otriangle) to read the six inputvalues.Note that scanf_scanreadasmanyvaluesasthereareformatitems.

    ArithmeticIfThe C/C++ language supports an expression form of the if statement called thearithmeticif. Whenusedaspartofalongerexpression,itshouldalwaysbeenclosedinparentheses.Again,thisisoneofthoseredundantlanguageformsthatwasintroducedtocaptureacodeoptimizationoptionatthemachinelevel.Thesemanticsarethesameastheifstatementexceptthatvaluesarebeingselectedasopposedtostatements.

    Inmodernpipelinedprocessors,gotooperations(ifwhile foretc.)canslowprocessing.Tomitigate thisdisadvantage,aconditionalassignment instruction is supported thatcanmakethearithmeticifevenmoreefficient.

    Theexamplesumsarangeofnumbersthathavea7intheonepositionora5inthetenspositione.g.71727515253154,butnot5,500,73,706.

    ArithmeticIfExample((Booleanexpression)?value-if-true:value-if-false)

    #includeintmain(void){inti,sum=0;for(i=56;i

  • SwitchStatementHuman as well as computer languages often have redundant ways of saying the samething. The C/C++ switch statement is redundant! It duplicates the function of themultiple if form, and even does that somewhat poorly as the switch statement isrestrictedtotestsforintegerequalitywhereastheBooleanexpressioninanifstatementcancompareanything.Sowhybother?Thereasontouseaswitchstatementisthatifthe multiple if tests involve consecutive integers (12 to 18 or a to z), mostarchitecturessupportasingle-instructionimplementation. Thatis,amultipleifwithahundred cases from ==1 to ==100would require 100 tests in theworst case. Thesame program fragment expressed as a switch statement requires only a single test!Switchstatementsarealsocommonlyusedtoimplementdecisiontablesorstatetables,whicharecomprisedofrowswithastatenumber,atest(usuallyoninputvalues),andanextstatenumber.

    SwitchStatementSyntax

    switch(IntegerExpression){caseIntegerOrChar:StatementListbreak;caseIntegerOrChar:caseIntegerOrChar:StatementListbreak;default:StatementList}/*switch*/

    1. Theexpressionandcaseselectorsmustbeanintegertype.2. Thecaseconstan