Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ •...
Transcript of Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ •...
Call-by-TypeFunctionsinC++Command-LineArgumentsinC++
CS16:SolvingProblemswithComputersILecture#5
ZiadMatni
Dept.ofComputerScience,UCSB
Administrative• CHANGEDT.A.OFFICE/OPENLABHOURS!– Thursday,10AM–12PM MuqsitNawaz– Friday,11AM–1PM XiyouZhou
• LinuxWorkshopTHISWeek!– HFHConferenceRoom(HFH1132)– Friday,April20th,1:00–2:30PM– Materialwillbeputupontheclasswebsite
• Your1stMidtermExamisNEXTTUESDAY(4/24)!!!– Omgomgomgomgomgomgomgomgomgomg
4/17/18 Matni,CS16,Sp18 2
• Tuesday,4/24inthisclassroom• Startsat2:00PM**SHARP**– Pleasestartarriving5-10minutesbeforeclass
• Imayaskyoutochangeseats• PleasebringyourUCSBIDswithyou
• Closedbook:nocalculators,nophones,nocomputers• OnlyallowedONE8.5”x11”sheetofnotes–onesidedonly– Youhavetoturnitinwithyourexam
• Youwillwriteyouranswersontheexamsheetitself.4/17/18 Matni,CS64,Wi18 3
What’sontheMidterm#1?FromtheLectures,including…
• IntrotoComputers,Programming,andC++• VariablesandAssignments• BooleanExpressions
(comparisonofvariables)• InputandOutputonStandardDevices
(cout,cin)• DataTypes,EscapeSequences,
FormattingDecimal• ArithmeticOperationsandtheirPriorities• BooleanLogicOperators• FlowofControl&ConditionalStatements
• Loops:for,while,do-while• TypesofErrorsinProgramming• MultiwayBranchingandtheswitch
command• GeneratingRandomNumbers• FunctionsinC++:
pre-defined,user-definedvoidfunctions,themain()functioncall-by-refvs.call-by-value
• CommandLineInputstoC++Programs• Separatecompilationsandmakefiles
4/17/18 Matni,CS16,Sp18 4
MidtermPrep
1. Lectureslides
2. Labprograms
3. Homeworkproblems
4. Bookchapters1thru5*
*checkwhichlectureslidesgowithit!!4/17/18 Matni,CS16,Sp18 5
LectureOutline
• voidfunctions• Call-by-valuevs.Call-by-referenceFunctions• Command-lineArguments
4/17/18 Matni,CS16,Sp18 6
ClassExercise1
• Let’swriteaprogramtogetherthatcontainsafunction,calledFallTime,thatcalculatesthetimeittakesforamasstobedroppedfromavariableheighth,giventheformula:
Algorithm:1. FallTimewilltakeasargument,d.Itwillreturnthevalueoft.2. main()willasktheuserforh(inmeters).3. main()willcallFallTime(h).4. main()willprintoutthevalueofFallTime(h)(inseconds).
4/17/18 Matni,CS16,Sp18 7
=sqrt(0.2038d)
ClassExercise2
• Let’swriteaprogramtogetherthatcontainsafunction,calledWriteIt,thattakesastringcalledmessageandanintegercalledr.Itthenprintsoutthestringrepeatedrtimeswithanexclamationmarkandspacebetweeneachrepetition.Thefunctiondoesnotreturnanything.
4/17/18 Matni,CS16,Sp18 8
Call-by-ValuevsCall-by-Reference
• Whenyoucallafunction,yourargumentsaregettingpassedonasvaluesintothefunction– Atleast,withwhatwe’veseensofar…– ThecallfuncX(a,b)passeson(intothefunction)thevaluesofaandb
• Seemslogicalenough…!?
• Youcanalsocallafunctionwithyourargumentsusedasreferencestotheactualvariablelocationinmemory– So,you’renotpassingthevariableitself,butit’slocationinmemory!– Whywouldwewanttodothat?
4/17/18 Matni,CS16,Sp18 9
ANS:Varsinsidefunctionsarelocaltothefunction!Whatifwewantedthemtochangeoutsideofit?
Call-by-ReferenceParameters
• “Call-by-reference”parametersallowustochangethevariableusedinthefunctioncall
• “Call-by-value”parametersdoNOTchangethevariableusedinthefunctioncall
• Intheexampleshownhere,theoutputwouldbe:xinfun1:9xinfun2:9a=5;b=9
• Weusetheampersandsymbol(&)todistinguishavariableasbeingcalled-by-reference,inafunctiondefinition
4/17/18 Matni,CS16,Sp18 10
intmain(){… … …
inta=5,b=5;fun1(a);fun2(b);cout<<"a="<<a<<";";cout<<"b="<<b<<endl;
… … … }voidfun1(intx)//callbyvalue{
x+=4;cout<<"xinfun1:"<<x<<endl;
}voidfun2(int&x)//callbyref.{
x+=4;cout<<"xinfun2:"<<x<<endl;
}
Whydidanotchange??Whydidbchange??
Call-by-ReferenceBehavior• Assumeintvariablesfirstandsecondareassignedmemoryaddresses1036and1040
(thisisusuallydonebythecompiler.Also,thesearemade-upmemoryaddresses…!)
• Nowafunctioncallexecutes:get_numbers(first,second);
• Thefunctionisdefinedas: voidget_numbers(int&first,int&second) { cout<<“Entertwointegers:”; cin>>first>>second; }
• Thefunctionmayaswellsay: voidget_numbers(theintvaratmemlocation1036,theintvaratmemlocation1040) { cout<<“Entertwointegers:” cin>>thevariableatmemorylocation1036; >>thevariableatmemorylocation1040; }
4/17/18 Matni,CS16,Sp18 11
Call-By-ReferenceDetails
• Thememorylocationoftheargumentvariableisgiventotheformalparameter– Nottheargumentvariableitself!
• Whateverisdonetoaformalparameterinsidethefunction,isactuallydonetothevalueatthememorylocationoftheargumentvariable– Asubtle,butimportant,difference!
• Ithastheeffectofmakingthecalled-by-referencevariableactlikeaglobalvar.– Ifitchangesinsidethefunction,itchangesoutsidethefunctiontoo– Butit’sbetterthanusingaglobalvariable!…(why?)
4/17/18 Matni,CS16,Sp18 12
voidfun2(int&x)//callbyref.
ClassExercise3• Let’swriteaprogramtogetherthatcontainsafunction,calledswap,thattakesatwointegervariablesasinputargumentsandcausestheirvaluestoswap,likeinthisexample:
inta=3,b=9;cout<<a<<";"<<b<<endl;//Thisshouldprintout“3;9”swap(a,b);cout<<a<<";"<<b<<endl;//Thisshouldprintout“9;3”
4/17/18 Matni,CS16,Sp18 13
Example:swap_valuesvoidswap(int&variable1,int&variable2){inttemp=variable1;variable1=variable2;variable2=temp;}
WecanONLYdothisifthefunctioniscall-by-reference!
4/17/18 Matni,CS16,Sp18 14
MixedParameterLists• Call-by-valueandcall-by-referenceparameters canbemixedinthesamefunction
• Example:voidgood_stuff(int&par1,intpar2,double&par3);
– par1andpar3arecall-by-referenceformalparameters• Changesinpar1andpar3changetheargumentvariable
– par2isacall-by-valueformalparameter• Changesinpar2donotchangetheargumentvariable
4/17/18 Matni,CS16,Sp18 15
Caution!InadvertentLocalVariables
• Forgettingtheampersand(&)createsacall-by-valueparameter– Youjustensuredthatavariablewillremainlocaltothefunction
(whenyourintentionwasNOTtodothat!)
• Thisisaharderrortodebug/find…becauseitlooksright!– So,becareful…
4/17/18 Matni,CS16,Sp18 16
4/17/18 Matni,CS16,Sp18 17
CommandLineArgumentswithC++
• InC++youcanacceptcommandlinearguments– Thatis,whenyouexecuteyourcode,youcanpassinputvaluesatthesametime
• Thesearearguments(inputs)thatarepassedintotheprogram fromtheOScommandline
• Forexample,fromtheLinuxOScommandline:$./addThese235$
4/17/18 Matni,CS16,Sp18 18
ßYou’repassing2and3asinputstotheprogramß andwhenit’sexecuted,theprogramgivesyouitsoutput(answer).
CommandLineArgumentswithC++
• Tousecommandlineargumentsinyourprogram, youmustadd2specialargumentstothemain()function
• Argument#1: Thenumberofelementsthatyouarepassingin:argc
• Argument#2:
Thefulllistofallofthecommandlineargumentsasanarray:*argv[] Thisisanarraypointer…nevermindthedetails,butmoreonthoseinalaterclass…
4/17/18 Matni,CS16,Sp18 19
CommandLineArgumentswithC++
• Themain()functionheadershouldbewrittenas: intmain(intargc,char*argv[]){…} insteadof intmain(){…}
• IntheOS,toexecutetheprogram,thecommandlineformshouldbe:
$program_nameargument1argument2…argumentnexample:
$sum_of_squares456
4/17/18 Matni,CS16,Sp18 20
4/17/18 Matni,CS16,Sp18 21
DEMO:intmain(intargc,char*argv[]){cout<<"Thereare"<<argc<<"argumentshere:"<<endl;cout<<"Let’sprintoutallthearguments:"<<endl;
for(inti=0;i<argc;i++) cout<<"argv["<<i<<"]is:"<<argv[i]<<endl;
return0;
}
argv[n]IsAlwaysaCharacterType!
• Whileargcisalwaysanint(it’scalculatedbythecompilerforyou)……allyougetfromthecommand-lineischaracterarrays– Thisisahold-outfromtheearlydaysofC(i.e.pre-C++)– So,thedatatypeofargumentbeingpassedisalwaysanarrayofcharacters(a.k.a.aC-string–moreonthoselaterinthequarter…)
• Totreatanargumentasanothertype(likeanumber,forinstance),youhavetofirstconvertitinsideyourprogram
• <cstdlib>libraryhaspre-definedfunctionstohelp!
4/17/18 Matni,CS16,Sp18 22
WhatIfIWantanArgumentThat’saNumber?
• Examples:atoi()andatof()Convertacharacterarrayintointanddouble,respectively.
Example:
4/17/18 Matni,CS16,Sp18 23
#include<iostream>#include<cstdlib>usingnamespacestd;intmain(intargc,char*argv[]){
intnum1=atoi(argv[1]);intnum2=atoi(argv[2]);intadd=num1+num2;intprod=num1*num2;cout<<num3<<endl;return0;
}
argv[]toint
argv[]todouble Thesefunctionsarein<cstdlib>
Thisistheonlywaythatwecandoarithmeticonthefirst2arguments
YOURTO-DOs
q DoLab3tomorrow(dueMonday)q DoHW5bynextThursday
q VisitProf’sandTAs‘officehoursifyouneedhelp!
q Eatyourvegetables
4/17/18 Matni,CS16,Sp18 24
4/17/18 Matni,CS16,Sp18 25