Parameter Passing Mechanisms Reference Parameters.

32
Parameter Passing Parameter Passing Mechanisms Mechanisms Reference Parameters

Transcript of Parameter Passing Mechanisms Reference Parameters.

Parameter Passing Parameter Passing MechanismsMechanisms

Reference Parameters

ProblemProblem

Using OCD, design and implement a Using OCD, design and implement a function that, given a string containing function that, given a string containing a long-distance telephone number, a long-distance telephone number, decomposes that number into its area decomposes that number into its area code, exchange, and local number.code, exchange, and local number.

Preliminary AnalysisPreliminary Analysis

Our function can receive the long-distance Our function can receive the long-distance phone number through a string parameter.phone number through a string parameter.

This problem requires that our function This problem requires that our function somehow communicate three values (area somehow communicate three values (area code, exchange, local number) to its caller.code, exchange, local number) to its caller.

A function cannot A function cannot returnreturn multiple values -- the multiple values -- the return statement only returns one value:return statement only returns one value:

return return ExpressionExpression ; ;

BehaviorBehavior

Our program should receive from its Our program should receive from its caller a long-distance phone number (a caller a long-distance phone number (a string). It should check that the string). It should check that the number is a valid long- distance number is a valid long- distance number. If so, it should compute and number. If so, it should compute and pass back its area code, exchange, and pass back its area code, exchange, and local number.local number.

ObjectsObjects

Description Type Movement NameDescription Type Movement Name

area code string out areaCodeexchange string out exchangelocal number string out localNum

long distance string in ldNumber number

OperationsOperations

Description Predefined? Library? NameDescription Predefined? Library? Name

receive a string yes built-in --select part of yes string substr a string

pass back 3 strings yes built-in ??

AlgorithmAlgorithm

0. Receive 0. Receive ldNumberldNumber from caller, plus ‘empty’ variables from caller, plus ‘empty’ variables areaCodeareaCode, , exchangeexchange and and localNumlocalNum..

1. Check that 1. Check that ldNumberldNumber is a long-distance number. is a long-distance number.

2. Fill 2. Fill areaCodeareaCode with appropriate substring of with appropriate substring of ldNumberldNumber..

3. Fill 3. Fill exchangeexchange with appropriate substring of with appropriate substring of ldNumberldNumber..

4. Fill 4. Fill localNumlocalNum with appropriate substring of with appropriate substring of ldNumberldNumber..

DiscussionDiscussion

Since a function cannot return 3 strings, Since a function cannot return 3 strings, we will instead require the caller to pass us we will instead require the caller to pass us three string variables, which our function three string variables, which our function will then “fill in” with the appropriate will then “fill in” with the appropriate values.values.

Normal parameters are called Normal parameters are called value value parametersparameters and are built as and are built as copiescopies of their of their arguments.arguments.

Changing a value parameter changes the Changing a value parameter changes the copy, not its corresponding argument.copy, not its corresponding argument.

SolutionSolution

Reference parametersReference parameters are parameters are parameters declared with an ampersand (&) following declared with an ampersand (&) following the parameter’s type (and before its the parameter’s type (and before its name).name).

A reference parameter is an A reference parameter is an aliasalias (i.e., (i.e., another name for) its corresponding another name for) its corresponding argument.argument.

Changing the value of a reference parameter Changing the value of a reference parameter changes the value of its corresponding changes the value of its corresponding argument.argument.

CodingCoding#include <string> // string class#include <cctype> // isdigit()using namespace std;

void ChopLDPhoneNumber(string ldNumber, // value: IN string & areaCode, // reference: OUT string & exchange, // reference: OUT string & localNum) // reference: OUT{ for (int i = 0; i < ldNumber.size(); i++) // check all assert(isdigit(ldNumber[i])); // digits

assert(ldNumber[0] == ‘1’ && // check for leading 1 ldNumber.size() == 11); // check number of digits

areaCode = ldNumber.substr(1, 3); exchange = ldNumber.substr(4, 3); localNum = ldNumber.substr(7, 4);}

TestingTesting

The caller must now supply a variable The caller must now supply a variable for each reference parameter, to be for each reference parameter, to be “filled in” by the function.“filled in” by the function.

cout << “Enter a L-D phone number: “;string original, part1, part2, part3;cin >> original;

ChopLDNumber(original, part1, part2, part3);

cout << “\nArea code: “ << part1 << “\nExchange: “ << part2 << “\nLocal number: “ << part3 << endl;

NotesNotes

When function ChopLDNumber() is called:When function ChopLDNumber() is called:– a a copycopy of argument of argument originaloriginal is made to is made to

create parameter create parameter ldNumberldNumber,,

– an an aliasalias of argument of argument part1part1 is made to create is made to create parameter parameter areaCodeareaCode,,

– an an aliasalias of argument of argument part2part2 is made to create is made to create parameter parameter exchangeexchange,,

– an an aliasalias of argument of argument part3part3 is made to create is made to create parameter parameter localNum.localNum.

0. Before the function call0. Before the function call

Memory

original

part1

part2

part3

16165551234

1. ldNumber is created1. ldNumber is createdas a copy of originalas a copy of original

Memory

original

part1

part2

part3

16165551234

ldNumber16165551234

2. areaCode is created2. areaCode is createdas an alias for part1as an alias for part1

Memory

original

part1

part2

part3

16165551234

ldNumber16165551234

areaCode

3. exchange is created3. exchange is createdas an alias for part2as an alias for part2

Memory

original

part1

part2

part3

16165551234

ldNumber16165551234

areaCode

exchange

3. localNum is created3. localNum is createdas an alias for part3as an alias for part3

Memory

original

part1

part2

part3

16165551234

ldNumber16165551234

areaCode

exchange

localNum

4. The function checks 4. The function checks ldNumber for validityldNumber for validity

Memory

original

part1

part2

part3

16165551234

ldNumber16165551234

areaCode

exchange

localNum

5. The function computes5. The function computesareaCode, changing part1areaCode, changing part1

Memory

original

part1

part2

part3

16165551234

ldNumber16165551234

areaCode

exchange

localNum

616

6. The function computes6. The function computesexchange, changing part2exchange, changing part2

Memory

original

part1

part2

part3

16165551234

ldNumber16165551234

areaCode

exchange

localNum

616

555

7. The function computes7. The function computeslocalNum, changing part3localNum, changing part3

Memory

original

part1

part2

part3

16165551234

ldNumber16165551234

areaCode

exchange

localNum

616

555

1234

8. The function returns, 8. The function returns, destroying all parametersdestroying all parameters

Memory

original

part1

part2

part3

16165551234

616

555

1234

9. part1, part2, and part39. part1, part2, and part3now contain the now contain the

information!information!

Memory

original

part1

part2

part3

16165551234

616

555

1234

NotesNotes

By default, parameters are By default, parameters are value parametersvalue parameters..

Reference parametersReference parameters are specified by placing are specified by placing an ampersand after the parameter’s type.an ampersand after the parameter’s type.

Reference parameters must be specified in Reference parameters must be specified in both a function’s both a function’s prototypeprototype and its and its definitiondefinition, or a linking error will occur., or a linking error will occur.

VariablesVariables must be passed as arguments for must be passed as arguments for reference parameters to fill, or a compiler reference parameters to fill, or a compiler error will occur.error will occur.

ConsiderConsider

Copying argument Copying argument originaloriginal consumes time. consumes time.

Creating an alias for an argument takes Creating an alias for an argument takes almost no time.almost no time.

We could speed up calls to our function by We could speed up calls to our function by making parameter making parameter ldNumberldNumber a reference a reference parameter.parameter.

However, we then run the risk of changing However, we then run the risk of changing originaloriginal if we mistakenly change if we mistakenly change ldNumberldNumber..

SolutionSolution

Constant reference parameters are Constant reference parameters are reference parameters whose declaration is reference parameters whose declaration is preceded by the keyword preceded by the keyword const. .

void ChopLDPhoneNumber(const string & ldNumber, // IN string & areaCode, // OUT string & exchange, // OUT string & localNum) // OUT// ...

Const reference parameters are Const reference parameters are read-onlyread-only reference parameters -- aliases of their reference parameters -- aliases of their arguments -- but they cannot be arguments -- but they cannot be changed. changed.

0. Before the function call0. Before the function call

Memory

original

part1

part2

part3

16165551234

1. ldNumber is created as 1. ldNumber is created as aa

const reference of originalconst reference of original

Memory

original

part1

part2

part3

16165551234 ldNumber

ConclusionConclusionThe rest of the function proceeds as before, except that all accesses to The rest of the function proceeds as before, except that all accesses to ldNumberldNumber now access now access originaloriginal instead of the copy. instead of the copy.

Any attempt to change Any attempt to change ldNumberldNumber will generate a compiler error (which makes sense, since its movement is IN, not OUT). will generate a compiler error (which makes sense, since its movement is IN, not OUT).

DiscussionDiscussionCopying time is not significant for Copying time is not significant for simple typessimple types (e.g., int, char, double, ...), but it is significant for (e.g., int, char, double, ...), but it is significant for class typesclass types (e.g., string, RandomInt, ...). (e.g., string, RandomInt, ...).

Use Use referencereference parameters for arguments whose movement is OUT. parameters for arguments whose movement is OUT.

Use Use const referenceconst reference parameters to store parameters to store class argumentsclass arguments whose movement is IN. whose movement is IN.

Use Use valuevalue parameters to store parameters to store simple type argumentssimple type arguments whose movement is IN. whose movement is IN.

SummarySummary

C++ provides 3 parameter mechanisms:C++ provides 3 parameter mechanisms:– value, used for IN parameters whose value, used for IN parameters whose

arguments are simple types.arguments are simple types.

– const reference, for IN parameters whose const reference, for IN parameters whose arguments are class types.arguments are class types.

– reference, for all OUT parameters.reference, for all OUT parameters.

AnnouncementAnnouncement

• Lab Test: Open books, Open notes. Lab Test: Open books, Open notes. – Wed. 2 hours.Wed. 2 hours.

– 3 programs.3 programs.

– You need prepare your money on your card.You need prepare your money on your card.

– You need to print all the results out in the lab.You need to print all the results out in the lab.

– You need in hand in the test sheet.You need in hand in the test sheet.