Upload
tjsimodlan
View
3
Download
2
Embed Size (px)
DESCRIPTION
C++
Citation preview
6/23/2015 ThePartsofaC++Program
http://aelinik.online.fr/cpp/ch02.htm#Heading2 1/10
Day2ThePartsofaC++Program
ASimpleProgramListing2.1.HELLO.CPPdemonstratesthepartsofaC++program.ABriefLookatcoutListing2.2.Usingcout.Comments
TypesofCommentsUsingComments
Listing2.3.HELP.CPPdemonstratescomments.CommentsattheTopofEachFileAFinalWordofCautionAboutComments
FunctionsListing2.4.Demonstratingacalltoafunction.
UsingFunctionsListing2.5.FUNC.CPPdemonstratesasimplefunction.SummaryQ&AWorkshop
QuizExercises
Day2
ThePartsofaC++Program
C++programsconsistofobjects,functions,variables,andothercomponentparts.Mostofthisbookisdevotedtoexplainingthesepartsindepth,buttogetasenseofhowaprogramfitstogetheryoumustseeacompleteworkingprogram.Todayyoulearn
ThepartsofaC++program.
Howthepartsworktogether.
Whatafunctionisandwhatitdoes.
ASimpleProgram
EventhesimpleprogramHELLO.CPPfromDay1,"GettingStarted,"hadmanyinterestingparts.Thissectionwillreviewthisprograminmoredetail.Listing2.1reproducestheoriginalversionofHELLO.CPPforyourconvenience.
6/23/2015 ThePartsofaC++Program
http://aelinik.online.fr/cpp/ch02.htm#Heading2 2/10
Listing2.1.HELLO.CPPdemonstratesthepartsofaC++program.
1:#include2:3:intmain()4:{5:cout
6/23/2015 ThePartsofaC++Program
http://aelinik.online.fr/cpp/ch02.htm#Heading2 3/10
AllANSIcompliantprogramsdeclaremain()toreturnanint.Thisvalueis"returned"totheoperatingsystemwhenyourprogramcompletes.Someprogrammerssignalanerrorbyreturningthevalue1.Inthisbook,main()willalwaysreturn0.
Themain()functionendsonline7withtheclosingbrace.
ABriefLookatcout
OnDay16,"Streams,"youwillseehowtousecouttoprintdatatothescreen.Fornow,youcanusecoutwithoutfullyunderstandinghowitworks.Toprintavaluetothescreen,writethewordcout,followedbytheinsertionoperator(
6/23/2015 ThePartsofaC++Program
http://aelinik.online.fr/cpp/ch02.htm#Heading2 4/10
Threevaluesarepassedtocoutonline7,andeachvalueisseparatedbytheinsertionoperator.Thefirstvalueisthestring"Hereis5:".Notethespaceafterthecolon.Thespaceispartofthestring.Next,thevalue5ispassedtotheinsertionoperatorandthenewlinecharacter(alwaysindoublequotesorsinglequotes).Thiscausestheline
Hereis5:5
tobeprintedtothescreen.Becausethereisnonewlinecharacterafterthefirststring,thenextvalueisprintedimmediatelyafterwards.Thisiscalledconcatenatingthetwovalues.
Online8,aninformativemessageisprinted,andthenthemanipulatorendlisused.Thepurposeofendlistowriteanewlinetothescreen.(OtherusesforendlarediscussedonDay16.)
Online9,anewformattingcharacter,\t,isintroduced.Thisinsertsatabcharacterandisusedonlines812tolineuptheoutput.Line9showsthatnotonlyintegers,butlongintegersaswellcanbeprinted.Line10demonstratesthatcoutwilldosimpleaddition.Thevalueof8+5ispassedtocout,but13isprinted.
Online11,thevalue5/8isinsertedintocout.Theterm(float)tellscoutthatyouwantthisvalueevaluatedasadecimalequivalent,andsoafractionisprinted.Online12thevalue7000*7000isgiventocout,andtheterm(double)isusedtotellcoutthatyouwantthistobeprintedusingscientificnotation.AllofthiswillbeexplainedonDay3,"VariablesandConstants,"whendatatypesarediscussed.
Online14,yousubstitutedyourname,andtheoutputconfirmedthatyouareindeedaC++programmer.Itmustbetrue,becausethecomputersaidso!
Comments
Whenyouarewritingaprogram,itisalwaysclearandselfevidentwhatyouaretryingtodo.Funnything,thoughamonthlater,whenyoureturntotheprogram,itcanbequiteconfusingandunclear.I'mnotsurehowthatconfusioncreepsintoyourprogram,butitalwaysdoes.
Tofighttheonsetofconfusion,andtohelpothersunderstandyourcode,you'llwanttousecomments.Commentsaresimplytextthatisignoredbythecompiler,butthatmayinformthereaderofwhatyouaredoingatanyparticularpointinyourprogram.
TypesofComments
C++commentscomeintwoflavors:thedoubleslash(//)comment,andtheslashstar(/*)comment.Thedoubleslashcomment,whichwillbereferredtoasaC++stylecomment,tellsthecompilertoignoreeverythingthatfollowsthiscomment,untiltheendoftheline.
Theslashstarcommentmarktellsthecompilertoignoreeverythingthatfollowsuntilitfindsastarslash(*/)commentmark.ThesemarkswillbereferredtoasCstylecomments.Every/*mustbematchedwithaclosing*/.
Asyoumightguess,CstylecommentsareusedintheClanguageaswell,butC++stylecommentsarenotpartoftheofficialdefinitionofC.
ManyC++programmersusetheC++stylecommentmostofthetime,andreserveCstylecommentsforblockingoutlargeblocksofaprogram.YoucanincludeC++stylecommentswithinablock
6/23/2015 ThePartsofaC++Program
http://aelinik.online.fr/cpp/ch02.htm#Heading2 5/10
"commentedout"byCstylecommentseverything,includingtheC++stylecomments,isignoredbetweentheCstylecommentmarks.
UsingComments
Asageneralrule,theoverallprogramshouldhavecommentsatthebeginning,tellingyouwhattheprogramdoes.Eachfunctionshouldalsohavecommentsexplainingwhatthefunctiondoesandwhatvaluesitreturns.Finally,anystatementinyourprogramthatisobscureorlessthanobviousshouldbecommentedaswell.
Listing2.3demonstratestheuseofcomments,showingthattheydonotaffecttheprocessingoftheprogramoritsoutput.
Listing2.3.HELP.CPPdemonstratescomments.
1:#include2:3:intmain()4:{5:/*thisisacomment6:anditextendsuntiltheclosing7:starslashcommentmark*/8:cout
6/23/2015 ThePartsofaC++Program
http://aelinik.online.fr/cpp/ch02.htm#Heading2 6/10
Arevisionhistory(notesoneachchangemade).
Whatcompilers,linkers,andothertoolswereusedtomaketheprogram.
Additionalnotesasneeded.
Forexample,thefollowingblockofcommentsmightappearatthetopoftheHelloWorldprogram.
/************************************************************
Program:HelloWorld
File:Hello.cpp
Function:Main(completeprogramlistinginthisfile)
Description:Printsthewords"Helloworld"tothescreen
Author:JesseLiberty(jl)
Environment:TurboC++version4,486/6632mbRAM,Windows3.1DOS6.0.EasyWinmodule.
Notes:Thisisanintroductory,sampleprogram.
Revisions:1.0010/1/94(jl)Firstrelease1.0110/2/94(jl)Capitalized"World"
************************************************************/
Itisveryimportantthatyoukeepthenotesanddescriptionsuptodate.Acommonproblemwithheaderslikethisisthattheyareneglectedaftertheirinitialcreation,andovertimetheybecomeincreasinglymisleading.Whenproperlymaintained,however,theycanbeaninvaluableguidetotheoverallprogram.
Thelistingsintherestofthisbookwillleaveofftheheadingsinanattempttosaveroom.Thatdoesnotdiminishtheirimportance,however,sotheywillappearintheprogramsprovidedattheendofeachweek.
AFinalWordofCautionAboutComments
Commentsthatstatetheobviousarelessthanuseful.Infact,theycanbecounterproductive,becausethecodemaychangeandtheprogrammermayneglecttoupdatethecomment.Whatisobvioustoonepersonmaybeobscuretoanother,however,sojudgmentisrequired.
Thebottomlineisthatcommentsshouldnotsaywhatishappening,theyshouldsaywhyitishappening.
DOaddcommentstoyourcode.DOkeepcommentsuptodate.DOusecommentstotellwhatasectionofcodedoes.DON'Tusecommentsforselfexplanatorycode.
Functions
Whilemain()isafunction,itisanunusualone.Typicalfunctionsarecalled,orinvoked,duringthecourseofyourprogram.Aprogramisexecutedlinebylineintheorderitappearsinyoursourcecode,
6/23/2015 ThePartsofaC++Program
http://aelinik.online.fr/cpp/ch02.htm#Heading2 7/10
untilafunctionisreached.Thentheprogrambranchesofftoexecutethefunction.Whenthefunctionfinishes,itreturnscontroltothelineofcodeimmediatelyfollowingthecalltothefunction.
Agoodanalogyforthisissharpeningyourpencil.Ifyouaredrawingapicture,andyourpencilbreaks,youmightstopdrawing,gosharpenthepencil,andthenreturntowhatyouweredoing.Whenaprogramneedsaserviceperformed,itcancallafunctiontoperformtheserviceandthenpickupwhereitleftoffwhenthefunctionisfinishedrunning.Listing2.4demonstratesthisidea.
Listing2.4.Demonstratingacalltoafunction.
1:#include2:3://functionDemonstrationFunction4://printsoutausefulmessage5:voidDemonstrationFunction()6:{7:cout
6/23/2015 ThePartsofaC++Program
http://aelinik.online.fr/cpp/ch02.htm#Heading2 8/10
Aparameterisadeclarationofwhattypeofvaluewillbepassedintheactualvaluepassedinbythecallingfunctioniscalledtheargument.Manyprogrammersusethesetwoterms,parametersandarguments,assynonyms.Othersarecarefulaboutthetechnicaldistinction.Thisbookwillusethetermsinterchangeably.
Thebodyofafunctionconsistsofanopeningbrace,zeroormorestatements,andaclosingbrace.Thestatementsconstitutetheworkofthefunction.Afunctionmayreturnavalue,usingareturnstatement.Thisstatementwillalsocausethefunctiontoexit.Ifyoudon'tputareturnstatementintoyourfunction,itwillautomaticallyreturnvoidattheendofthefunction.Thevaluereturnedmustbeofthetypedeclaredinthefunctionheader.
NOTE:FunctionsarecoveredinmoredetailonDay5,"Functions."Thetypesthatcanbereturnedfromafunctionarecoveredinmoredet+[radical][Delta][infinity]onDay3.Theinformationprovidedtodayistopresentyouwithanoverview,becausefunctionswillbeusedinalmostallofyourC++programs.
Listing2.5demonstratesafunctionthattakestwointegerparametersandreturnsanintegervalue.Don'tworryaboutthesyntaxorthespecificsofhowtoworkwithintegervalues(forexample,intx)fornowthatiscoveredindetailonDay3.
Listing2.5.FUNC.CPPdemonstratesasimplefunction.
1:#include2:intAdd(intx,inty)3:{4:5:cout
6/23/2015 ThePartsofaC++Program
http://aelinik.online.fr/cpp/ch02.htm#Heading2 9/10
ThefunctionAdd()isdefinedonline2.Ittakestwointegerparametersandreturnsanintegervalue.Theprogramitselfbeginsonline9andonline11,whereitprintsamessage.Theprogrampromptstheuserfortwonumbers(lines13to15).Theusertypeseachnumber,separatedbyaspace,andthenpressestheEnterkey.main()passesthetwonumberstypedinbytheuserasargumentstotheAdd()functiononline17.
ProcessingbranchestotheAdd()function,whichstartsonline2.Theparametersaandbareprintedandthenaddedtogether.Theresultisreturnedonline6,andthefunctionreturns.
Inlines14and15,thecinobjectisusedtoobtainanumberforthevariablesaandb,andcoutisusedtowritethevaluestothescreen.Variablesandotheraspectsofthisprogramareexploredindepthinthenextfewdays.
Summary
Thedifficultyinlearningacomplexsubject,suchasprogramming,isthatsomuchofwhatyoulearndependsoneverythingelsethereistolearn.ThischapterintroducedthebasicpartsofasimpleC++program.Italsointroducedthedevelopmentcycleandanumberofimportantnewterms.
Q&A
Q.Whatdoes#includedo?
A.Thisisadirectivetothepreprocessor,whichrunswhenyoucallyourcompiler.Thisspecificdirectivecausesthefilenamedafterthewordincludetobereadin,asifitweretypedinatthatlocationinyoursourcecode.
Q.Whatisthedifferencebetween//commentsand/*stylecomments?
A.Thedoubleslashcomments(//)"expire"attheendoftheline.Slashstar(/*)commentsareineffectuntilaclosingcomment(*/).Remember,noteventheendofthefunctionterminatesaslashstarcommentyoumustputintheclosingcommentmark,oryouwillgetacompiletimeerror.
Q.Whatdifferentiatesagoodcommentfromabadcomment?
A.Agoodcommenttellsthereaderwhythisparticularcodeisdoingwhateveritisdoingorexplainswhatasectionofcodeisabouttodo.Abadcommentrestateswhataparticularlineofcodeisdoing.Linesofcodeshouldbewrittensothattheyspeakforthemselves.Readingthelineofcodeshouldtellyouwhatitisdoingwithoutneedingacomment.
Workshop
TheWorkshopprovidesquizquestionstohelpyousolidifyyourunderstandingofthematerialcoveredandexercisestoprovideyouwithexperienceinusingwhatyou'velearned.TrytoanswerthequizandexercisequestionsbeforecheckingtheanswersinAppendixD,andmakesureyouunderstandtheanswersbeforecontinuingtothenextchapter.
Quiz
6/23/2015 ThePartsofaC++Program
http://aelinik.online.fr/cpp/ch02.htm#Heading2 10/10
1.Whatisthedifferencebetweenthecompilerandthepreprocessor?
2.Whyisthefunctionmain()special?
3.Whatarethetwotypesofcomments,andhowdotheydiffer?
4.Cancommentsbenested?
5.Cancommentsbelongerthanoneline?
Exercises
1.WriteaprogramthatwritesIloveC++tothescreen.
2.Writethesmallestprogramthatcanbecompiled,linked,andrun.
3.BUGBUSTERS:Enterthisprogramandcompileit.Whydoesitfail?Howcanyoufixit?
1:#include2:voidmain()3:{4:cout