Parameters

• We use parameters to move information between the calling and called functions.
• There are two types of parameters.
• A value parameter transfers information from the calling function to the called function.
• A reference parameter allows transfer of information both ways.
• If the information is not returned, choose a value parameter.
• For simple data types, (int, char, bool,...) use a reference parameter only when the parameter is used to return information.
• We will change this rule later, but it is a good start.
• Syntax
• type identifier  for value
•  type & identifier for reference.
• Let's write a pass by value function, FixShift
• This takes an integer and maps it to the proper value between 0 and 26.
• We can't just mod, because mod works "differently" with negative numbers.
• So if a number is negative, we will just repeatedly add 26 to it until it becomes positive.
• The mod by 26.
• The function is passed an integer.
• The function returns an integer.
• int FixShift(int value) {
while(value < 0) {
value += 26;
}

return value % 26;
}
• We might call this function in GetShift
• int GetShift() {
int userShift{0};
int realShift{0};

cout << "Enter the shift amount => ";
cin >> userShift;
cout << endl;

cin.ignore(100,'\n');

realShift = FixShift(userShift);
return realShift;
}
• Remember, when a function is called, the values inside () are called arguments.
• Trace this code showing how the data is transferred. (This is a chalk board exercise, so Zach, you better write this one down).
• Note that changing the parameter has no impact on the argument.
• We could write this as a reference function that returns no value.
• void FixShift2(int & value) {
while(value < 0) {
value += 26;
}

value %= 26;

return;
}
• And a new GetShift
• int GetShift2() {
int userShift{0};

cout << "Enter the shift amount => ";
cin >> userShift;
cout << endl;

cin.ignore(100,'\n');

FixShift2(userShift);
return userShift;
}
• Trace this one.
• Note changing the parameter also changes the argument.
• Each of these is equally valid.
• So how do I pick?
• I tend to use value returning functions
• I like value returning functions for formula like actions.
• If I have more than one return value, I select reference parameters.
• When using reference parameters, I only use a return value to indicate errors or some other meta value.
• Sometimes when I am sloppy I will mix the two.
• If I don't want to make a copy of something, I select reference parameters. More on this later.
• If you will be passing in a constant, that must be done via a value parameter.
• If you are passing in an open file stream, that must be done via a reference parameter.