25
Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5 Ziad Matni Dept. of Computer Science, UCSB

Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

  • Upload
    others

  • View
    57

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

Call-by-TypeFunctionsinC++Command-LineArgumentsinC++

CS16:SolvingProblemswithComputersILecture#5

ZiadMatni

Dept.ofComputerScience,UCSB

Page 2: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

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

Page 3: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

•  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

Page 4: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

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

Page 5: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

MidtermPrep

1.  Lectureslides

2.  Labprograms

3.  Homeworkproblems

4.  Bookchapters1thru5*

*checkwhichlectureslidesgowithit!!4/17/18 Matni,CS16,Sp18 5

Page 6: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

LectureOutline

•  voidfunctions•  Call-by-valuevs.Call-by-referenceFunctions•  Command-lineArguments

4/17/18 Matni,CS16,Sp18 6

Page 7: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

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)

Page 8: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

ClassExercise2

•  Let’swriteaprogramtogetherthatcontainsafunction,calledWriteIt,thattakesastringcalledmessageandanintegercalledr.Itthenprintsoutthestringrepeatedrtimeswithanexclamationmarkandspacebetweeneachrepetition.Thefunctiondoesnotreturnanything.

4/17/18 Matni,CS16,Sp18 8

Page 9: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

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?

Page 10: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

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??

Page 11: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

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

Page 12: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

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.

Page 13: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

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

Page 14: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

Example:swap_valuesvoidswap(int&variable1,int&variable2){inttemp=variable1;variable1=variable2;variable2=temp;}

WecanONLYdothisifthefunctioniscall-by-reference!

4/17/18 Matni,CS16,Sp18 14

Page 15: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

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

Page 16: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

Caution!InadvertentLocalVariables

•  Forgettingtheampersand(&)createsacall-by-valueparameter–  Youjustensuredthatavariablewillremainlocaltothefunction

(whenyourintentionwasNOTtodothat!)

•  Thisisaharderrortodebug/find…becauseitlooksright!– So,becareful…

4/17/18 Matni,CS16,Sp18 16

Page 17: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

4/17/18 Matni,CS16,Sp18 17

Page 18: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

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).

Page 19: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

CommandLineArgumentswithC++

•  Tousecommandlineargumentsinyourprogram, youmustadd2specialargumentstothemain()function

•  Argument#1: Thenumberofelementsthatyouarepassingin:argc

•  Argument#2:

Thefulllistofallofthecommandlineargumentsasanarray:*argv[] Thisisanarraypointer…nevermindthedetails,butmoreonthoseinalaterclass…

4/17/18 Matni,CS16,Sp18 19

Page 20: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

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

Page 21: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

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;

}

Page 22: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

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

Page 23: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

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

Page 24: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

YOURTO-DOs

q DoLab3tomorrow(dueMonday)q DoHW5bynextThursday

q VisitProf’sandTAs‘officehoursifyouneedhelp!

q Eatyourvegetables

4/17/18 Matni,CS16,Sp18 24

Page 25: Call-by-Type Functions in C++ Command-Line Arguments in C++ · Command Line Arguments with C++ • In C++ you can accept command line arguments – That is, when you execute your

4/17/18 Matni,CS16,Sp18 25