0% found this document useful (0 votes)
13 views

Lec4. C++ Function Parameters, Overloading, and Arrays

This document discusses function parameters, overloading, and arrays in C++. It covers topics like call-by-value vs call-by-reference parameters, default arguments, resolving overloaded functions, and basic array usage.

Uploaded by

Majd AL Kawaas
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Lec4. C++ Function Parameters, Overloading, and Arrays

This document discusses function parameters, overloading, and arrays in C++. It covers topics like call-by-value vs call-by-reference parameters, default arguments, resolving overloaded functions, and basic array usage.

Uploaded by

Majd AL Kawaas
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Chapters 4 & 5

Function Parameters,
Overloading, and
Arrays

Copyright © 2017 Pearson Education, Ltd.


All rights reserved.
Parameters
• Two methods of passing arguments as parameters
• Call-by-value
– Copy of actual argument passed
– Considered "local variable" inside function
– If modified, only "local copy" changes
• Function has no access to "actual argument“ from caller

• Call-by-reference
– "address of" actual argument is passed
– Used to provide access to caller’s actual argument
– Caller’s data can be modified by called function!
– Typically used for input function
• To retrieve data for caller
• Data is then "given" to caller
– Specified by ampersand, &, after type in formal parameter list
4-2
Call-by-Value Example:
Formal Parameter Used as
a Local Variable

Welcome to the law office of


Dewey, Cheatham, and Howe.
The law office with a heart.
Enter the hours and minutes of your consultation:
5 46
For 5 hours and 46 minutes, your bill is $3450.00

4-3
#include <iostream>
using namespace std;
int main () {
// declare simple variables
int i, j=10;
// declare reference variables
int & s = i;

i = 5;
cout << "Address of i : "<< &i<<endl;
cout << "Value of i : " << i << endl;
int& r = i;
cout << "Address of r : " << &r<<endl;
cout << "Value of r : " << r << endl;
r=j;
cout << "Address of i : "<< &i<<endl;
cout << "Value of i : " << i << endl;
i = 11;
cout << "Value of s : " << s << endl;
cout << "Value of r : " << r << endl;
return 0;
}
4-4
//Program to demonstrate call-by-reference parameters .Call-By-Reference
#include <iostream> Parameter
using namespace std; Example
void getNumbers(int& input1, int& input2); //Reads two integers from the keyboard .
void swapValues(int& variable1, int& variable2); //Interchanges the values.
void showResults(int output1, int output2); //Shows the values of output1 and output2 .
int main( ) {
int firstNum, secondNum;
getNumbers(firstNum, secondNum);
swapValues(firstNum, secondNum);
showResults(firstNum, secondNum);
return 0;
}
void getNumbers(int& input1, int& input2) {
cout << "Enter two integers: ";
cin >> input1 >> input2;
}
void swapValues(int& variable1, int& variable2){
int temp;
temp = variable1; Enter two integers: 5 6
variable1 = variable2;
In reverse order the numbers are: 6 5
variable2 = temp;
}
void showResults(int output1, int output2){
cout << "In reverse order the numbers are: "
<< output1 << " " << output2 << endl;
} 4-5
Call-By-Reference Details
• What’s really passed in?
– A "reference" back to caller’s actual argument!
• Refers to memory location of actual argument
• Called "address", which is a unique number referring to distinct place in memory

• Constant Reference Parameters


– Reference arguments inherently "dangerous"
• Caller’s data can be changed
• Often this is desired, sometimes not
– To "protect" data, & still pass by reference:
• Use const keyword
void sendConstRef(const int &par1, const int &par2);
– Makes arguments "read-only" by function
– No changes allowed inside function body 4-6
//Illustrates the difference between a call-by-value
//parameter and a call-by-reference parameter .
Comparing
#include <iostream> Argument
using namespace std;
void doStuff(int par1Value, int& par2Ref);
Mechanisms
//par1Value is a call-by-value formal parameter and
//par2Ref is a call-by-reference formal parameter .
int main( ) {
par1Value in function call = 111
int n1, n2;
par2Ref in function call = 222
n1 = 1;
n1 after function call = 1
n2 = 2;
n2 after function call = 222
doStuff(n1, n2);
cout << "n1 after function call = " << n1 << endl;
cout << "n2 after function call = " << n2 << endl;
return 0;
}
void doStuff(int par1Value, int& par2Ref) {
par1Value = 111;
cout << "par1Value in function call = “ << par1Value << endl;
par2Ref = 222;
cout << "par2Ref in function call = " << par2Ref << endl;
}
4-7
Parameters and Arguments
• often used interchangeably
• True meanings:
– Formal parameters : In function declaration and function definition
– Arguments: Used to "fill-in" a formal parameter
• In function call (argument list)
– Call-by-value & Call-by-reference
• Simply the "mechanism" used in plug-in process

• Mixed Parameter Lists


– Parameter lists can include pass-by-value and pass-by-reference parameters
– Order of arguments in list is critical:
void mixedCall(int & par1, int par2, double & par3);
mixedCall(arg1, arg2, arg3);
– arg1 must be integer type, is passed by reference
– arg2 must be integer type, is passed by value
– arg3 must be double type, is passed by reference 4-8
Overloading
• Same function name but different parameter list
– two functions with same name, one computes average of 2 numbers and
another one computes the average of 3 numbers
• Function "signature"
– Function name & parameter list
– Must be "unique" for each function definition

double average(double n1, double n2) {


return ((n1 + n2) / 2.0);
}

double average(double n1, double n2, double n3){


return ((n1 + n2) / 2.0);
}

avg = average(5.2, 6.7); //Calls "two-parameter average()"


avg = average(6.5, 8.5, 4.2); //Calls "three-parameter average()"
4-9
Overloading
Function
Example

The average of 2.0, 2.5, and 3.0 is 2.5


The average of 4.5 and 5.5 is 5.0

4-10
Overloading Resolution
• C++ function call resolution:
– 1st: looks for exact signature (Exact Match)
• Looks for exact signature where no argument conversion required
– 2nd: looks for "compatible" signature (Compatible Match)
• Looks for "compatible" signature where automatic type conversion is possible:
– 1st with promotion (e.g., intdouble) no loss of data
– 2nd with demotion (e.g., doubleint) Possible loss of data

• Example Given following functions:


– 1. void f(int n, double m);
2. void f(double n, int m);
3. void f(int n, int m);
– These calls:
f(98, 99);  Calls #3
f(5.3, 4);  Calls #2
f(4.3, 5.2);  Calls ???
• Avoid such confusing overloading 4-11
Automatic Type Conversion and Overloading
• Numeric formal parameters typically made "double" type
• Allows for "any" numeric type
– Any "subordinate" data automatically promoted
• int  double
• float  double
• char  double *More on this later!

• Avoids overloading for different numeric types


double mpg(double miles, double gallons){
return (miles/gallons);
}

• mpgComputed = mpg(5, 20);


– Converts 5 & 20 to doubles, then passes
• mpgComputed = mpg(5.8, 20.2);
– No conversion necessary
• mpgComputed = mpg(5, 2.4);
– Converts 5 to 5.0, then passes values to function 4-12
Default Arguments
• Allows omitting some arguments
• Specified in function declaration/prototype
void showVolume(int length, int width=1, int height=1);
• Last 2 arguments are defaulted
– Possible calls:
• showVolume(2, 4, 6); //All arguments supplied
• showVolume(3, 5); //height defaulted to 1
• showVolume(7); //width & height defaulted to 1

4-13
Default
Arguments
Example:

Volume of a box with


Length = 4, Width = 6
and Height = 2 is 48
Volume of a box with
Length = 4, Width = 6
and Height = 1 is 24
Volume of a box with
Length = 4, Width = 1
and Height = 1 is 4

4-14
Introduction to Arrays
• Array definition: a collection of data of same type
– Avoids declaring multiple simple variables
• Declare the array  allocates memory
int score[5]; //Declares array of 5 integers named "score"
• In declaration, specifies SIZE of array
• Value in brackets called index or subscript: Numbered from 0 to size - 1
• Access using index/subscript
cout << score[3];

• for-loops: works well "counting through" elements of an array


for (idx = 0; idx<5; idx++)
{
cout << score[idx] << "off by "
<< max – score[idx] << endl;
}

5-15
Array Program
Example:
Enter 5 scores:
5 9 2 10 6
The highest score is 10
The scores and their
differences from the highest are:
5 off by 5
9 off by 1
2 off by 8
10 off by 0
6 off by 4

5-16
Major Array Pitfall
• Array indexes always start with zero!
• Zero is "first" number to computer scientists
• C++ will "let" you go beyond range
– Unpredictable results
– Compiler will not detect these errors!
• Example: double t[24]; // 24 is array size
// Declares array of 24 double values called temperature
– They are indexed as: t[0], t[1] … t[23]
– Common mistake: t[24] = 5;
• Index 24 is "out of range"!
• No warning, possibly disastrous results
5-17
Defined Constant as Array Size
• Always use defined/named constant for array size
• Example: const int NUMBER_OF_STUDENTS = 5;
int score[NUMBER_OF_STUDENTS];
– Improves readability
– Improves versatility
– Improves maintainability
• Use everywhere size of array is needed
– In for-loop for traversal:
for (idx = 0; idx < NUMBER_OF_STUDENTS; idx++){
// Manipulate array
}
– In calculations involving size:
lastIndex = (NUMBER_OF_STUDENTS – 1);
– If size changes  requires only ONE change in program!

5-18
Arrays in Memory
• Array declarations allocate memory for entire array
• Sequentially-allocated: Means addresses allocated "back-to-back"
– Allows indexing calculations
• Simple "addition" from array beginning (index 0)

5-19
Initializing Arrays
• As simple variables can be initialized at declaration:
int price = 0; // 0 is initial value
• Arrays can as well: int children[3] = {2, 12, 1};
– Equivalent to following: int children[3];
children[0] = 2;
children[1] = 12;
children[2] = 1;

• Auto-Initializing Arrays
– If fewer values than size supplied:
• Fills from beginning, fills "rest" with zero of array base type
– If array-size is left out
• Declares array with size required based on number of initialization values
• Example: int b[] = {5, 12, 11};
– Allocates array b to size 3
5-20
Arrays in Functions
• As arguments to functions
– Indexed variables: An individual "element" of an array can be function
parameter
– Entire arrays: All array elements can be passed as "one entity"
• As return value from function

• Indexed variable handled same as simple variable of array base type


– Given this function declaration: void myFunction(double par1);
– And these declarations: int i; double n, a[10];
– Can make these function calls:
myFunction(i); // i is converted to double
myFunction(a[3]); // a[3] is double
myFunction(n); // n is double

• Formal parameter can be entire array


– Argument then passed in function call is array name, called "array parameter"
– Send size of array as well as second parameter
5-21
Example: Function with Entire Array as
Argument
void fillUp( int a[], int size);
//Precondition: size is the declared size of the array a .
//The user will type in size integers .
//Postcondition: The array a is filled with size integers
//from the keyboard .
void fillUp( int a[], int size) {
cout << "Enter " << size << " numbers:\n";
for ( int i = 0; i < size; i++)
cin >> a[i];
cout << "The last array index used is "
<< (size – 1) << endl;
}

• In some main() function definition, consider this calls:


int score[5], numberOfScores = 5;
fillup(score, numberOfScores);
– 1st argument is entire array
– 2nd argument is integer value
– Note no brackets in array argument! 5-22
Array as Argument: how?
• What’s really passed?
– Think of array as 3 "pieces"
• Address of first indexed variable (arrName[0])
• Array base type
• Size of array
– Only 1st piece is passed!
• Just the beginning address of array
• Very similar to "pass-by-reference"

• Functions that Return an Array


– Functions cannot return arrays same way simple types are
returned
– Requires use of a "pointer"
– Will be discussed in chapter 10…
5-23
Searching an Array (1 of 2)
//Searches a partially filled array of nonnegative integers .
#include <iostream>
using namespace std;
const int DECLARED_SIZE = 20;
void fillArray( int a[], int size, int & numberUsed);
int search( const int a[], int numberUsed, int target);
int main( ) {
int arr[DECLARED_SIZE], listSize, target;
fillArray(arr, DECLARED_SIZE, listSize);
char ans;
int result;
do {
cout << "Enter a number to search for: ";
cin >> target;
result = search(arr, listSize, target);
if (result == –1)
cout << target << " is not on the list.\n";
else
cout << target << " is stored in array position "
<< result << endl;
cout << "Search again?(y/n followed by Return): ";
cin << ans;
} while ((ans != 'n') && (ans != 'N'));
cout << "End of program.\n";
return 0; 5-24
}
void fillArray( int a[], int size, int & numberUsed) { Searching an Array
cout << "Enter up to " << size
<< " nonnegative whole numbers.\n"
<< "Mark the end of the list with a negative number.\n";
int next, index = 0;
cin >> next;
while ((next >= 0) && (index < size)){
a[index] = next;
index++;
cin >> next;
}
numberUsed = index;
}
int search( const int a[], int numberUsed, int target){
int index = 0;
bool found = false ;
while ((!found) && (index < numberUsed))
if (target == a[index])
found = true ;
else
index++;
if (found)
return index;
else
return –1;
} 5-25
This program reads golf scores and shows
how much each differs from the average.
Enter golf scores:
Enter up to 10 nonnegative whole numbers.
Mark the end of the list with a negative
number.
69 74 68 -1
Average of the 3 scores = 70.3333
The scores are:
69 differs from average by –1.33333
74 differs from average by 3.66667
68 differs from average by –2.33333

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 5-26


Multidimensional Arrays
• Arrays with more than one index: Two indexes: An "array of arrays"
– char page[30][100];
• Visualize as:
page[0][0], page[0][1], …, page[0][99]
page[1][0], page[1][1], …, page[1][99]

page[29][0], page[29][1], …, page[29][99]

• Similar to one-dimensional array


– 1st dimension size not given, provided as second parameter,
– 2nd dimension size IS given
void DisplayPage(const char p[][100], int sizeDimension1)
{
for (int index1=0; index1<sizeDimension1; index1++)
{
for (int index2=0; index2 < 100; index2++)
cout << p[index1][index2];
cout << endl;
}
}
5-27

You might also like