Anda di halaman 1dari 10

6/23/2015

ThePartsofaC++Program

Day2
ThePartsofaC++Program
ASimpleProgram
Listing2.1.HELLO.CPPdemonstratesthepartsofaC++program.
ABriefLookatcout
Listing2.2.
Usingcout.
Comments
TypesofComments
UsingComments
Listing2.3.HELP.CPPdemonstratescomments.
CommentsattheTopofEachFile
AFinalWordofCautionAboutComments
Functions
Listing2.4.Demonstratingacalltoafunction.
UsingFunctions
Listing2.5.FUNC.CPPdemonstratesasimplefunction.
Summary
Q&A
Workshop
Quiz
Exercises

Day2
ThePartsofaC++Program
C++programsconsistofobjects,functions,variables,andothercomponentparts.Mostofthisbookis
devotedtoexplainingthesepartsindepth,buttogetasenseofhowaprogramfitstogetheryoumustsee
acompleteworkingprogram.Todayyoulearn
ThepartsofaC++program.
Howthepartsworktogether.
Whatafunctionisandwhatitdoes.

ASimpleProgram
EventhesimpleprogramHELLO.CPPfromDay1,"GettingStarted,"hadmanyinterestingparts.This
sectionwillreviewthisprograminmoredetail.Listing2.1reproducestheoriginalversionof
HELLO.CPPforyourconvenience.
http://aelinik.online.fr/cpp/ch02.htm#Heading2

1/10

6/23/2015

ThePartsofaC++Program

Listing2.1.HELLO.CPPdemonstratesthepartsofaC++program.
1:#include<iostream.h>
2:
3:intmain()
4:{
5:cout<<"HelloWorld!\n";
6:return0;
7:}
HelloWorld!

Online1,thefileiostream.hisincludedinthefile.Thefirstcharacteristhe#symbol,whichisasignal
tothepreprocessor.Eachtimeyoustartyourcompiler,thepreprocessorisrun.Thepreprocessorreads
throughyoursourcecode,lookingforlinesthatbeginwiththepoundsymbol(#),andactsonthoselines
beforethecompilerruns.
includeisapreprocessorinstructionthatsays,"Whatfollowsisafilename.Findthatfileandreaditin
righthere."Theanglebracketsaroundthefilenametellthepreprocessortolookinalltheusualplacesfor
thisfile.Ifyourcompilerissetupcorrectly,theanglebracketswillcausethepreprocessortolookforthe
fileiostream.hinthedirectorythatholdsalltheHfilesforyourcompiler.Thefileiostream.h(Input
OutputStream)isusedbycout,whichassistswithwritingtothescreen.Theeffectofline1istoinclude
thefileiostream.hintothisprogramasifyouhadtypeditinyourself.
NewTerm:Thepreprocessorrunsbeforeyourcompilereachtimethecompilerisinvoked.The
preprocessortranslatesanylinethatbeginswithapoundsymbol(#)intoaspecialcommand,getting
yourcodefilereadyforthecompiler.
Line3beginstheactualprogramwithafunctionnamedmain().EveryC++programhasamain()
function.Ingeneral,afunctionisablockofcodethatperformsoneormoreactions.Usuallyfunctions
areinvokedorcalledbyotherfunctions,butmain()isspecial.Whenyourprogramstarts,main()iscalled
automatically.
main(),likeallfunctions,muststatewhatkindofvalueitwillreturn.Thereturnvaluetypeformain()in
HELLO.CPPisvoid,whichmeansthatthisfunctionwillnotreturnanyvalueatall.Returningvalues
fromfunctionsisdiscussedindetailonDay4,"ExpressionsandStatements."
Allfunctionsbeginwithanopeningbrace({)andendwithaclosingbrace(}).Thebracesforthemain()
functionareonlines4and7.Everythingbetweentheopeningandclosingbracesisconsideredapartof
thefunction.
Themeatandpotatoesofthisprogramisonline5.Theobjectcoutisusedtoprintamessagetothe
screen.We'llcoverobjectsingeneralonDay6,"BasicClasses,"andcoutanditsrelatedobjectcinin
detailonDay17,"ThePreprocessor."Thesetwoobjects,coutandcin,areusedinC++toprintstrings
andvaluestothescreen.Astringisjustasetofcharacters.
Here'showcoutisused:typethewordcout,followedbytheoutputredirectionoperator(<<).Whatever
followstheoutputredirectionoperatoriswrittentothescreen.Ifyouwantastringofcharacterswritten,
besuretoenclosethemindoublequotes("),asshownonline5.
NewTerm:Atextstringisaseriesofprintablecharacters.
Thefinaltwocharacters,\n,tellcouttoputanewlineafterthewordsHelloWorld!Thisspecialcodeis
explainedindetailwhencoutisdiscussedonDay17.
http://aelinik.online.fr/cpp/ch02.htm#Heading2

2/10

6/23/2015

ThePartsofaC++Program

AllANSIcompliantprogramsdeclaremain()toreturnanint.Thisvalueis"returned"totheoperating
systemwhenyourprogramcompletes.Someprogrammerssignalanerrorbyreturningthevalue1.In
thisbook,main()willalwaysreturn0.
Themain()functionendsonline7withtheclosingbrace.

ABriefLookatcout
OnDay16,"Streams,"youwillseehowtousecouttoprintdatatothescreen.Fornow,youcanusecout
withoutfullyunderstandinghowitworks.Toprintavaluetothescreen,writethewordcout,followed
bytheinsertionoperator(<<),whichyoucreatebytypingthelessthancharacter(<)twice.Eventhough
thisistwocharacters,C++treatsitasone.
Followtheinsertioncharacterwithyourdata.Listing2.2illustrateshowthisisused.Typeinthe
exampleexactlyaswritten,exceptsubstituteyourownnamewhereyouseeJesseLiberty(unlessyour
nameisJesseLiberty,inwhichcaseleaveitjustthewayitisit'sperfectbutI'mstillnotsplitting
royalties!).

Listing2.2.Usingcout.
1://Listing2.2usingcout
2:
3:#include<iostream.h>
4:intmain()
5:{
6:cout<<"Hellothere.\n";
7:cout<<"Hereis5:"<<5<<"\n";
8:cout<<"Themanipulatorendlwritesanewlinetothescreen."<<
endl;
9:cout<<"Hereisaverybignumber:\t"<<70000<<endl;
10:cout<<"Hereisthesumof8and5:\t"<<8+5<<endl;
11:cout<<"Here'safraction:\t\t"<<(float)5/8<<endl;
12:cout<<"Andaveryverybignumber:\t"<<(double)7000*7000<<
endl;
13:cout<<"Don'tforgettoreplaceJesseLibertywithyourname...\n";
14:cout<<"JesseLibertyisaC++programmer!\n";
15:return0;
16:}
Hellothere.
Hereis5:5
Themanipulatorendlwritesanewlinetothescreen.
Hereisaverybignumber:70000
Hereisthesumof8and5:13
Here'safraction:0.625
Andaveryverybignumber:4.9e+07
Don'tforgettoreplaceJesseLibertywithyourname...
JesseLibertyisaC++programmer!

Online3,thestatement#include<iostream.h>causestheiostream.hfiletobeaddedtoyoursource
code.Thisisrequiredifyouusecoutanditsrelatedfunctions.
Online6isthesimplestuseofcout,printingastringorseriesofcharacters.Thesymbol\nisaspecial
formattingcharacter.Ittellscouttoprintanewlinecharactertothescreen.
http://aelinik.online.fr/cpp/ch02.htm#Heading2

3/10

6/23/2015

ThePartsofaC++Program

Threevaluesarepassedtocoutonline7,andeachvalueisseparatedbytheinsertionoperator.Thefirst
valueisthestring"Hereis5:".Notethespaceafterthecolon.Thespaceispartofthestring.Next,the
value5ispassedtotheinsertionoperatorandthenewlinecharacter(alwaysindoublequotesorsingle
quotes).Thiscausestheline
Hereis5:5

tobeprintedtothescreen.Becausethereisnonewlinecharacterafterthefirststring,thenextvalueis
printedimmediatelyafterwards.Thisiscalledconcatenatingthetwovalues.
Online8,aninformativemessageisprinted,andthenthemanipulatorendlisused.Thepurposeofendl
istowriteanewlinetothescreen.(OtherusesforendlarediscussedonDay16.)
Online9,anewformattingcharacter,\t,isintroduced.Thisinsertsatabcharacterandisusedonlines8
12tolineuptheoutput.Line9showsthatnotonlyintegers,butlongintegersaswellcanbeprinted.
Line10demonstratesthatcoutwilldosimpleaddition.Thevalueof8+5ispassedtocout,but13is
printed.
Online11,thevalue5/8isinsertedintocout.Theterm(float)tellscoutthatyouwantthisvalue
evaluatedasadecimalequivalent,andsoafractionisprinted.Online12thevalue7000*7000isgiven
tocout,andtheterm(double)isusedtotellcoutthatyouwantthistobeprintedusingscientificnotation.
AllofthiswillbeexplainedonDay3,"VariablesandConstants,"whendatatypesarediscussed.
Online14,yousubstitutedyourname,andtheoutputconfirmedthatyouareindeedaC++programmer.
Itmustbetrue,becausethecomputersaidso!

Comments
Whenyouarewritingaprogram,itisalwaysclearandselfevidentwhatyouaretryingtodo.Funny
thing,thoughamonthlater,whenyoureturntotheprogram,itcanbequiteconfusingandunclear.I'm
notsurehowthatconfusioncreepsintoyourprogram,butitalwaysdoes.
Tofighttheonsetofconfusion,andtohelpothersunderstandyourcode,you'llwanttousecomments.
Commentsaresimplytextthatisignoredbythecompiler,butthatmayinformthereaderofwhatyouare
doingatanyparticularpointinyourprogram.
TypesofComments
C++commentscomeintwoflavors:thedoubleslash(//)comment,andtheslashstar(/*)comment.The
doubleslashcomment,whichwillbereferredtoasaC++stylecomment,tellsthecompilertoignore
everythingthatfollowsthiscomment,untiltheendoftheline.
Theslashstarcommentmarktellsthecompilertoignoreeverythingthatfollowsuntilitfindsastarslash
(*/)commentmark.ThesemarkswillbereferredtoasCstylecomments.Every/*mustbematchedwith
aclosing*/.
Asyoumightguess,CstylecommentsareusedintheClanguageaswell,butC++stylecommentsare
notpartoftheofficialdefinitionofC.
ManyC++programmersusetheC++stylecommentmostofthetime,andreserveCstylecommentsfor
blockingoutlargeblocksofaprogram.YoucanincludeC++stylecommentswithinablock
http://aelinik.online.fr/cpp/ch02.htm#Heading2

4/10

6/23/2015

ThePartsofaC++Program

"commentedout"byCstylecommentseverything,includingtheC++stylecomments,isignored
betweentheCstylecommentmarks.
UsingComments
Asageneralrule,theoverallprogramshouldhavecommentsatthebeginning,tellingyouwhatthe
programdoes.Eachfunctionshouldalsohavecommentsexplainingwhatthefunctiondoesandwhat
valuesitreturns.Finally,anystatementinyourprogramthatisobscureorlessthanobviousshouldbe
commentedaswell.
Listing2.3demonstratestheuseofcomments,showingthattheydonotaffecttheprocessingofthe
programoritsoutput.

Listing2.3.HELP.CPPdemonstratescomments.
1:#include<iostream.h>
2:
3:intmain()
4:{
5:/*thisisacomment
6:anditextendsuntiltheclosing
7:starslashcommentmark*/
8:cout<<"HelloWorld!\n";
9://thiscommentendsattheendoftheline
10:cout<<"Thatcommentended!\n";
11:
12://doubleslashcommentscanbealoneonaline
13:/*ascanslashstarcomments*/
14:return0;
15:}
HelloWorld!
Thatcommentended!

Thecommentsonlines5through7arecompletelyignoredbythecompiler,as
arethecommentsonlines9,12,and13.Thecommentonline9endedwiththe
endoftheline,however,whilethecommentsonlines5and13requiredaclosingcommentmark.
CommentsattheTopofEachFile
Itisagoodideatoputacommentblockatthetopofeveryfileyouwrite.Theexactstyleofthisblockof
commentsisamatterofindividualtaste,buteverysuchheadershouldincludeatleastthefollowing
information:
Thenameofthefunctionorprogram.
Thenameofthefile.
Whatthefunctionorprogramdoes.
Adescriptionofhowtheprogramworks.
Theauthor'sname.
http://aelinik.online.fr/cpp/ch02.htm#Heading2

5/10

6/23/2015

ThePartsofaC++Program

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.1
DOS6.0.EasyWinmodule.
Notes:Thisisanintroductory,sampleprogram.
Revisions:1.0010/1/94(jl)Firstrelease
1.0110/2/94(jl)Capitalized"World"
************************************************************/

Itisveryimportantthatyoukeepthenotesanddescriptionsuptodate.Acommonproblemwithheaders
likethisisthattheyareneglectedaftertheirinitialcreation,andovertimetheybecomeincreasingly
misleading.Whenproperlymaintained,however,theycanbeaninvaluableguidetotheoverallprogram.
Thelistingsintherestofthisbookwillleaveofftheheadingsinanattempttosaveroom.Thatdoesnot
diminishtheirimportance,however,sotheywillappearintheprogramsprovidedattheendofeach
week.
AFinalWordofCautionAboutComments
Commentsthatstatetheobviousarelessthanuseful.Infact,theycanbecounterproductive,becausethe
codemaychangeandtheprogrammermayneglecttoupdatethecomment.Whatisobvioustoone
personmaybeobscuretoanother,however,sojudgmentisrequired.
Thebottomlineisthatcommentsshouldnotsaywhatishappening,theyshouldsaywhyitishappening.
DOaddcommentstoyourcode.DOkeepcommentsuptodate.DOusecommentstotell
whatasectionofcodedoes.DON'Tusecommentsforselfexplanatorycode.

Functions
Whilemain()isafunction,itisanunusualone.Typicalfunctionsarecalled,orinvoked,duringthe
courseofyourprogram.Aprogramisexecutedlinebylineintheorderitappearsinyoursourcecode,
http://aelinik.online.fr/cpp/ch02.htm#Heading2

6/10

6/23/2015

ThePartsofaC++Program

untilafunctionisreached.Thentheprogrambranchesofftoexecutethefunction.Whenthefunction
finishes,itreturnscontroltothelineofcodeimmediatelyfollowingthecalltothefunction.
Agoodanalogyforthisissharpeningyourpencil.Ifyouaredrawingapicture,andyourpencilbreaks,
youmightstopdrawing,gosharpenthepencil,andthenreturntowhatyouweredoing.Whenaprogram
needsaserviceperformed,itcancallafunctiontoperformtheserviceandthenpickupwhereitleftoff
whenthefunctionisfinishedrunning.Listing2.4demonstratesthisidea.

Listing2.4.Demonstratingacalltoafunction.
1:#include<iostream.h>
2:
3://functionDemonstrationFunction
4://printsoutausefulmessage
5:voidDemonstrationFunction()
6:{
7:cout<<"InDemonstrationFunction\n";
8:}
9:
10://functionmainprintsoutamessage,then
11://callsDemonstrationFunction,thenprintsout
12://asecondmessage.
13:intmain()
14:{
15:cout<<"Inmain\n";
16:DemonstrationFunction();
17:cout<<"Backinmain\n";
18:return0;
19:}
Inmain
InDemonstrationFunction
Backinmain

ThefunctionDemonstrationFunction()isdefinedonlines57.Whenitiscalled,itprintsamessageto
thescreenandthenreturns.
Line13isthebeginningoftheactualprogram.Online15,main()printsoutamessagesayingitisin
main().Afterprintingthemessage,line16callsDemonstrationFunction().Thiscallcausesthe
commandsinDemonstrationFunction()toexecute.Inthiscase,theentirefunctionconsistsofthecodeon
line7,whichprintsanothermessage.WhenDemonstrationFunction()completes(line8),itreturnsback
towhereitwascalledfrom.Inthiscasetheprogramreturnstoline17,wheremain()printsitsfinalline.
UsingFunctions
Functionseitherreturnavalueortheyreturnvoid,meaningtheyreturnnothing.Afunctionthataddstwo
integersmightreturnthesum,andthuswouldbedefinedtoreturnanintegervalue.Afunctionthatjust
printsamessagehasnothingtoreturnandwouldbedeclaredtoreturnvoid.
Functionsconsistofaheaderandabody.Theheaderconsists,inturn,ofthereturntype,thefunction
name,andtheparameterstothatfunction.Theparameterstoafunctionallowvaluestobepassedintothe
function.Thus,ifthefunctionweretoaddtwonumbers,thenumberswouldbetheparameterstothe
function.Here'satypicalfunctionheader:
intSum(inta,intb)
http://aelinik.online.fr/cpp/ch02.htm#Heading2

7/10

6/23/2015

ThePartsofaC++Program

Aparameterisadeclarationofwhattypeofvaluewillbepassedintheactualvaluepassedinbythe
callingfunctioniscalledtheargument.Manyprogrammersusethesetwoterms,parametersand
arguments,assynonyms.Othersarecarefulaboutthetechnicaldistinction.Thisbookwillusetheterms
interchangeably.
Thebodyofafunctionconsistsofanopeningbrace,zeroormorestatements,andaclosingbrace.The
statementsconstitutetheworkofthefunction.Afunctionmayreturnavalue,usingareturnstatement.
Thisstatementwillalsocausethefunctiontoexit.Ifyoudon'tputareturnstatementintoyourfunction,
itwillautomaticallyreturnvoidattheendofthefunction.Thevaluereturnedmustbeofthetype
declaredinthefunctionheader.
NOTE:FunctionsarecoveredinmoredetailonDay5,"Functions."Thetypesthatcanbe
returnedfromafunctionarecoveredinmoredet+[radical][Delta][infinity]onDay3.The
informationprovidedtodayistopresentyouwithanoverview,becausefunctionswillbe
usedinalmostallofyourC++programs.
Listing2.5demonstratesafunctionthattakestwointegerparametersandreturnsanintegervalue.Don't
worryaboutthesyntaxorthespecificsofhowtoworkwithintegervalues(forexample,intx)fornow
thatiscoveredindetailonDay3.

Listing2.5.FUNC.CPPdemonstratesasimplefunction.
1:#include<iostream.h>
2:intAdd(intx,inty)
3:{
4:
5:cout<<"InAdd(),received"<<x<<"and"<<y<<"\n";
6:return(x+y);
7:}
8:
9:intmain()
10:{
11:cout<<"I'minmain()!\n";
12:inta,b,c;
13:cout<<"Entertwonumbers:";
14:cin>>a;
15:cin>>b;
16:cout<<"\nCallingAdd()\n";
17:c=Add(a,b);
18:cout<<"\nBackinmain().\n";
19:cout<<"cwassetto"<<c;
20:cout<<"\nExiting...\n\n";
21:return0;
22:}
I'minmain()!
Entertwonumbers:35
CallingAdd()
InAdd(),received3and5
Backinmain().
cwassetto8
Exiting...
http://aelinik.online.fr/cpp/ch02.htm#Heading2

8/10

6/23/2015

ThePartsofaC++Program

ThefunctionAdd()isdefinedonline2.Ittakestwointegerparametersandreturnsanintegervalue.The
programitselfbeginsonline9andonline11,whereitprintsamessage.Theprogrampromptstheuser
fortwonumbers(lines13to15).Theusertypeseachnumber,separatedbyaspace,andthenpressesthe
Enterkey.main()passesthetwonumberstypedinbytheuserasargumentstotheAdd()functiononline
17.
ProcessingbranchestotheAdd()function,whichstartsonline2.Theparametersaandbareprintedand
thenaddedtogether.Theresultisreturnedonline6,andthefunctionreturns.
Inlines14and15,thecinobjectisusedtoobtainanumberforthevariablesaandb,andcoutisusedto
writethevaluestothescreen.Variablesandotheraspectsofthisprogramareexploredindepthinthe
nextfewdays.

Summary
Thedifficultyinlearningacomplexsubject,suchasprogramming,isthatsomuchofwhatyoulearn
dependsoneverythingelsethereistolearn.Thischapterintroducedthebasic
partsofasimpleC++program.Italsointroducedthedevelopmentcycleandanumberofimportantnew
terms.

Q&A
Q.Whatdoes#includedo?
A.Thisisadirectivetothepreprocessor,whichrunswhenyoucallyourcompiler.Thisspecific
directivecausesthefilenamedafterthewordincludetobereadin,asifitweretypedinatthat
locationinyoursourcecode.
Q.Whatisthedifferencebetween//commentsand/*stylecomments?
A.Thedoubleslashcomments(//)"expire"attheendoftheline.Slashstar(/*)commentsarein
effectuntilaclosingcomment(*/).Remember,noteventheendofthefunctionterminatesaslash
starcommentyoumustputintheclosingcommentmark,oryouwillgetacompiletimeerror.
Q.Whatdifferentiatesagoodcommentfromabadcomment?
A.Agoodcommenttellsthereaderwhythisparticularcodeisdoingwhateveritisdoingor
explainswhatasectionofcodeisabouttodo.Abadcommentrestateswhataparticularlineof
codeisdoing.Linesofcodeshouldbewrittensothattheyspeakforthemselves.Readingtheline
ofcodeshouldtellyouwhatitisdoingwithoutneedingacomment.

Workshop
TheWorkshopprovidesquizquestionstohelpyousolidifyyourunderstandingofthematerialcovered
andexercisestoprovideyouwithexperienceinusingwhatyou'velearned.Trytoanswerthequizand
exercisequestionsbeforecheckingtheanswersinAppendixD,andmakesureyouunderstandthe
answersbeforecontinuingtothenextchapter.
Quiz
http://aelinik.online.fr/cpp/ch02.htm#Heading2

9/10

6/23/2015

ThePartsofaC++Program

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:#include<iostream.h>
2:voidmain()
3:{
4:cout<<Isthereabughere?";
5:}

4.FixthebuginExercise3andrecompile,link,andrunit.

http://aelinik.online.fr/cpp/ch02.htm#Heading2

10/10

Anda mungkin juga menyukai