Structures as Arguments

advertisement
Structure Programming
Lecture 9
Chapter 5 - Function – part II
22 March 2016
1
Outlines
• Structures
• Structures as Arguments
• Returning Structure Variables
•
Reference and Reference Parameters
•
Argument Passing by value
•
Argument Passing by reference
•
Pass by Reference (with and without the const keyword)
• Passing Structures by Reference
• Enumerators
22 March 2016
2
STRUCTURES AS ARGUMENTS
RETURNING STRUCTURE VARIABLES
22 March 2016
3
Structures as Arguments
• Example: English system of measurement
The main() part of this program accepts one distances
in feet-and-inches format from the user, and places
these values in the structures, d1 . It then calls a
function, engldisp(), that takes a Distance structure
variable as an argument. The purpose of the function
is to display the distance passed to it in the standard
format, such as 10’–2.25”.
22 March 2016
4
Structures as Arguments
• Example: English system of measurement
#include <iostream>
using namespace std;
struct Distance
{
int feet;
float inches;
};
//English distance
void engldisp( Distance );
22 March 2016
//declaration
5
Structures as Arguments, cont.
int main()
{
Distance d1, d2;
cout << “Enter feet: “;
cout << “Enter inches: “;
cout << “\nEnter feet: “;
cout << “Enter inches: “;
cout << “\nd1 = “;
engldisp(d1);
cout << “\nd2 = “;
engldisp(d2);
cout << endl;
return 0;
//define two lengths
//get length d1 from user
cin >> d1.feet;
cin >> d1.inches;
//get length d2 from user
cin >> d2.feet;
cin >> d2.inches;
//display length 1
//display length 2
}
22 March 2016
6
Structures as Arguments, cont.
void engldisp( Distance dd ) //parameter dd of type Distance
{
cout << dd.feet << “\’-” << dd.inches << “\””;
}
• Here’s some sample interaction with the program:
Enter feet: 6
Enter inches: 4
Enter feet: 5
Enter inches: 4.25
d1 = 6’-4”
d2 = 5’-4.25”
22 March 2016
7
22 March 2016
8
Returning Structure Variables
• Example: Write a function to add variables of type
Distance and returns a value of this same type:
The program asks the user for two lengths, in feet-andinches format, adds them together by calling the
function addengl(), and displays the results using the
engldisp() function introduced in the ENGLDISP
program.
22 March 2016
9
Returning Structure Variables
• Example: Write a function to add variables of type Distance and
returns a value of this same type:
#include <iostream>
using namespace std;
struct Distance
{
int feet;
float inches;
};
//English distance
Distance addengl(Distance, Distance);
void engldisp(Distance);
22 March 2016
//declarations
10
int main()
{
Distance d1, d2, d3;
cout << “\nEnter feet: “;
cout << “Enter inches: “;
cout << “\nEnter feet: “;
cout << “Enter inches: “;
//define three lengths
//get length d1 from user
cin >> d1.feet;
cin >> d1.inches;
//get length d2 from user
cin >> d2.feet;
cin >> d2.inches;
d3 = addengl(d1, d2);
//d3 is sum of d1 and d2
cout << endl;
engldisp(d1);
cout << “ + “; //display all lengths
engldisp(d2);
cout << “ = “;
engldisp(d3);
cout << endl;
return 0;
}
22 March 2016
11
// adds two structures of type Distance, returns sum
Distance addengl( Distance dd1, Distance dd2 )
{
Distance dd3;
//define a new structure for sum
dd3.inches = dd1.inches + dd2.inches; //add the inches
dd3.feet = dd1.feet + dd2.feet;
//add the feet
if(dd3.inches >= 12.0)
//if inches >= 12.0,
{
//then decrease inches
dd3.inches -= 12.0;
//by 12.0 and
dd3.feet++;
//increase feet by 1
}
return dd3;
//return structure
}
22 March 2016
12
void engldisp( Distance dd )
{
cout << dd.feet << “\’-” << dd.inches << “\””;
}
• Here’s some output from the program:
Enter feet: 4
Enter inches: 5.5
Enter feet: 5
Enter inches: 6.5
4’-5.5” + 5’-6.5” = 10’-0”
22 March 2016
13
Argument Passing By …
22 March 2016
14
Reference Parameters “Argument Passing”

There are two ways to pass arguments to functions in C++:



Pass by VALUE




Pass by VALUE
Pass by REFERENCE
The value of a variable is passed along to the function
The function creates copies of the argument passed to it.
If the function modifies that value, the modifications stay within the
scope of that function and do not affect the original variable’s value
in memory.
Pass by REFERENCE



A reference to the variable is passed along to the function.
The called function access the caller’s data directly.
If the function modifies that value, the modifications appear also
within the scope of the calling function, i.e. The function can change
the original variable’s value in memory.
22 March 2016
15
Reference variables
• References can also be used as aliases for other
variables within a function.
• Reference variables must be initialized in their
declarations and cannot be reassigned as aliases to
other variables.
• Once a reference is declared as an alias for another
variable, all operations supposedly performed on the
alias are actually performed on the original variable.
22 March 2016
16
References, cont.
22 March 2016
17
PASS BY REFERENCE
(WITH AND WITHOUT THE CONST
KEYWORD)
22 March 2016
18
const Function Arguments
• Suppose you want to pass an argument by reference
for efficiency, but not only do you want the function
not to modify it, you want a guarantee that the
function cannot modify it.
• To obtain such a guarantee, you can apply the const
modifier to the variable in the function declaration.
22 March 2016
19
Example
void aFunc(int& a, const int& b); //declaration
void main()
{
int alpha = 7;
int beta = 11;
aFunc(alpha, beta);
}
//-------------------------------------------------------------void aFunc(int& a, const int& b) //definition
{
a = 107;
//OK
b = 111;
//error: can’t modify constant argument
22
} March 2016
20
Passing Structures By Reference
22 March 2016
21
Pass structures by Reference
• Why use Pass By Reference? Because you are passing a large
structure…
• If an argument is large, then passing by reference is more
efficient because, only an address is really passed, not the
entire variable.
• Example:
performs scale conversions on values of type Distance:
• A scale conversion involves multiplying a group of distances by
a factor.
• If a distance is 6’–8”, and a scale factor is 0.5, the new distance
is 3’–4”.
• Such a conversion might be applied to all the dimensions of a
building to make the building shrink but remain in proportion.
22 March 2016
22
Example
performs scale conversions on values of type Distance…
#include <iostream>
using namespace std;
//////////////////////////////////////////////////////////st
struct Distance
//English distance
{ int feet;
float inches;
};
void scale( Distance &, float );
void engldisp( const Distance &);
22 March 2016
//function
//declarations
23
int main()
{
Distance d1 = { 12, 6.5 };
Distance d2 = { 10, 5.5 };
cout << “d1 = “; engldisp(d1);
cout << “\nd2 = “; engldisp(d2);
scale(d1, 0.5);
scale(d2, 0.25);
cout << “\nd1 = “; engldisp(d1);
cout << “\nd2 = “; engldisp(d2);
cout << endl;
return 0;
}
22 March 2016
//initialize d1 and d2
//display old d1 and d2
//scale d1 and d2
//display new d1 and d2
24
void scale( Distance& dd, float factor)
{
float inches = (dd.feet*12 + dd.inches) * factor;
dd.feet = static_cast<int>(inches / 12);
dd.inches = inches - dd.feet * 12;
}
void engldisp( const Distance& dd ) //parameter dd of type distance
{
cout << dd.feet << “\’-” << dd.inches << “\””;
}
cast a variable: the data is coerced into becoming another
type before used it. The expression
static_cast<datatype>(Var) or datatype(Var) or
22 March 2016
(datatype)Var
25
• Here’s the program’s output:
d1 = 12’-6.5”
d2 = 10’-5.5”
d1 = 6’-3.25”
d2 = 2’-7.375”
22 March 2016
26
Be careful with Pass By Reference?
bool isfeetset (Distance &dis)
{
if (dis.feet = 0)
return true;
return false;
}



Recognize the familiar bug?
What’s worse is that you’ve permit the parameter modification in
the scope of the calling function as well!
Can you protect against this?
22 March 2016
27
Be careful with Pass By Reference
You can specify that a parameter cannot be modified:
bool isfeetset (const Distance &dis)
{
if (dis.feet = 0) //error
return true;
return false;
}


By adding the const keyword in front of the argument
declaration, you tell the compiler that this parameter must not
be changed by the function.
Any attempts to change it will generate a compile time error.
22 March 2016
28
Enumerations
Enumerations
Enumerations
• structures can be looked at as a way to provide userdefined data types.
• A different approach to defining your own data type is
the enumeration.
• An enumeration is a list of all possible values. In an
enum you must give a specific name to every possible
value.
enum days_of_week { Sun, Mon, Tue, Wed, Thu, Fri, Sat
};
• Ordinarily the first name in the list is given the value 0,
the next name is given the value 1, and so on.
• you can define variables of this type.
days_of_week day1, day2;
Example
• Write program uses an enumeration for the days of the week.
enum days_of_week { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
void main()
{
days_of_week day1, day2;
//define variables
day1 = Mon;
//give values to
day2 = Fri;
//variables
int diff = day2 - day1;
//can do integer arithmetic
cout << “Days between = “ << diff << endl;
if(day1 < day2)
//can do comparisons
cout << “day1 comes before day2\n”;
}
Specifying Integer Values
• if you want the suits to start with 1 instead of 0, you
can say
enum Suit { clubs=1, diamonds, hearts, spades };
• Subsequent names are given values starting at this
point, so diamonds is 2, hearts is 3, and spades is 4.
enum type and C++ input/output (I/O)
• enum type is not recognized by C++ input/output (I/O)
statements.
enum direction { north, south, east, west };
direction dir1 = south;
cout << dir1;
• the output would be 1.
Your Turn (1/2)
• 9. True or false: When arguments are passed by value, the
function works with the original arguments in the calling
program.
• 11. Which of the following can legitimately be passed to a
function?
a. A constant
b. A variable
c. A structure
d. A header file
22 March 2016
34
Your Turn (2/2)
• 18. When an argument is passed by reference
a. a variable is created in the function to hold the argument’s
value.
b. the function cannot access the argument’s value.
c. a temporary variable is created in the calling program to
hold the argument’s value.
d. the function accesses the argument’s original value in the
calling program.
22 March 2016
35
Answers
• 9- false.
• 11- a,b,c.
• 18- d.
Download