Arguments – Parameters
|
In order to carry its assignment, a function might be supplied
something. For example, when a function is used to calculate the area of
a square, you have to supply the side of the square, then the function
will work from there. On the other hand, a function used to get a
student’s first name may not have a need; its job would be to supply or
return something.
Some functions have needs and some do not. The
needs of a function are provided between parentheses. These needs could
be as varied as possible. If a function does not have a need, leave its
parentheses empty.
In some references, instead of leaving the
parentheses empty, the programmer would write void. In this book, if a
function does not have a need, we will leave its parentheses empty.
Some functions will have only one need, some
others will have many. A function’s need is called an Argument. If a
function has a lot of needs, these are its arguments.
The argument is a valid variable and is
defined by its data type and a name. For example, if a function is
supposed to calculate the area of a square and it is expecting to
receive the side of the square, you can declare it as
double CalculateArea(double Side);
A function used to get a student’s first name could be declared as:
string FirstName();
Here are examples of declaring functions; some take arguments, some don’t:
double CalculateArea(double Side); char Answer(); void Message(float Distance); bool InTheBox(char Mine); string StudentName(); double RectangleArea(double Length, double Width); void DefaultBehavior(int Key, double Area, char MI, float Ter); |
Techniques of Passing Arguments
|
In order to perform its assignment, a function may need arguments. Any
function that wants to use the result of another function must supply
the other function’s required arguments, if any. When declaring a
function that uses arguments, specify each argument with a data type and
a name.
|
Passing Arguments by Value
|
To use a function inside of another function, that is, to call a
function from another function, specify the name of the function and its
list of arguments (if any) inside of parentheses; only the name of each
argument is needed. You can declare a function like this:
float GetHours(string FullName);
To call such a function from another, you would use:
GetHours(FullName);
Here is an example:
#include <iostream> #include <string> using namespace std; string GetName() { string FirstName, LastName, FN; cout << "Employee's First Name: "; cin >> FirstName; cout << "Employee's Last Name: "; cin >> LastName; FN = FirstName + " " + LastName; return FN; } int main() { string FullName; double Hours; double GetHours(string FullName); FullName = GetName(); Hours = GetHours(FullName); cout << "\nEmployee's Name: " << FullName; cout << "\nWeekly Hours: " << Hours << " hours\n\n"; return 0; } double GetHours(string FullName) { double Mon, Tue, Wed, Thu, Fri, TotalHours; cout << endl << FullName << "'s Weekly Hours\n"; cout << "Monday: "; cin >> Mon; cout << "Tuesday: "; cin >> Tue; cout << "Wednesday: "; cin >> Wed; cout << "Thursday: "; cin >> Thu; cout << "Friday: "; cin >> Fri; TotalHours = Mon + Tue + Wed + Thu + Fri; return TotalHours; }
Here is an example of running the program:
Employee's First Name: Frank Employee's Last Name: Dassault Frank Dassault's Weekly Hours Monday: 8.00 Tuesday: 8.50 Wednesday: 9.00 Thursday: 8.00 Friday: 8.00 Employee's Name: Frank Dassault Weekly Hours: 41.5 hours
When declaring a function, the compiler does
not require that you supply a name for each argument, it only needs to
know what type of
argument(s) and how many arguments a function takes. This means
that the
GetHours() function could have been declared as
float GetHours(string);
Furthermore, the compiler does not care about
the name you give an argument when declaring a function. Imagine you
want to write a function that would calculate an item’s purchase price
based on the item’s store price added the tax. The tax rate is a
percentage value. This means that a tax rate set at 7.50% in C++ terms
is equal to 0.075 (because 7.50/100 = 0.075). The tax amount collected
on a purchase is taken from an item’s price; its formula is:
TaxRate
Tax Amount = Item Price * 100
The formula of calculating the final price of an item is:
Final Price = Item Price + Tax Amount
Here is an example:
#include <iostream> using namespace std; int main() { double itemPrice, taxRate; double PurchasePrice(double itemPrice, double taxRate); cout << "Enter the price of the item: "; cin >> itemPrice; cout << "Enter the tax rate: "; cin >> taxRate; cout << "\nThe final price is: " << PurchasePrice(itemPrice, taxRate); cout << "\n\n"; return 0; } double PurchasePrice(double itemPrice, double taxRate) { double price; price = itemPrice + (itemPrice * taxRate / 100); return price; }
Here is an example of running the program:
Enter the price of the item: 125.95 Enter the tax rate: 5.75 The final price is: 133.192 |
Passing Arguments by Reference
|
When you declare a variable in a program, the compiler reserves an
amount of space for that variable. If you need to use that variable
somewhere in your program, you call it and make use of its value. There
are two major issues related to a variable: its value and its location
in the memory.
|
The location of a variable in memory is referred to as its address.
If you supply the argument using its name, the
compiler only makes a copy of the argument’s value and gives it to the
calling function. Although the calling function receives the argument’s
value and can use in any way, it cannot (permanently) alter it. C++
allows a calling function to modify the value of a passed argument if
you find it necessary. If you want the calling function to modify the
value of a supplied argument and return the modified value, you should
pass the argument using its reference.
To pass an argument as a reference, when
declaring the function, precede the argument name with an ampersand
“&”. You can pass 0, one, or more arguments as reference in the
program or pass all arguments as reference. The decision as to which
argument(s) should be passed by value or by reference is based on
whether or not you want the called function to modify the argument and
permanently change its value.
Here are examples of passing some arguments by reference:
void Area(double &side); // The argument is passed by reference bool Decision(char &answer, int age); // One argument is passed by reference // All arguments are passed by reference float Purchase(float &discountPrice, float &newDiscount, char &commission);
You add the ampersand when declaring a
function and/or when defining it. When calling the function, supply only
the name of the referenced argument(s). The above would be called with:
Area(side); Decision(answer, Age); Purchase(discountPrice, newDiscount, commission);
Imagine that you write a function that
calculates employees weekly salary provided the total weekly hours and
hourly rate. To illustrate our point, we will see how or whether one
function can modify a salary of an employee who claims to have worked
more than the program displays. The starting regular program would be as
follows:
#include <iostream> using namespace std; int main() { float hours, rate, wage; void Earnings(float h, float r); cout << "Enter the total Weekly hours: "; cin >> hours; cout << "Enter the employee's hourly rate: "; cin >> rate; cout << "\nIn the main() function,"; cout << "\n\tWeekly Hours = " << hours; cout << "\n\tSalary = $" << rate; cout << "\n\tWeekly Salary: $" << hours * rate; cout << "\nCalling the Earnings() function"; Earnings(hours, rate); cout << "\n\nAfter calling the Earnings() function, " << "in the main() function,"; cout << "\n\tWeekly Hours = " << hours; cout << "\n\tSalary = " << rate; cout << "\n\tWeekly Salary: " << hours * rate; return 0; } void Earnings(float thisWeek, float salary) { cout << "\n\nIn the Earnings() function,"; cout << "\n\tWeekly Hours = " << thisWeek; cout << "\n\tSalary = " << salary; cout << "\n\tWeekly Salary= " << thisWeek * Salary; }
If you test the program by typing 32 for the
weekly hours and 6.45 for the salary, you would notice the weekly values
are the same.
Imagine that the employee claims to have
worked 42 hours instead of the passed weekly hours. You could create the
following function to find out.
void Earnings(float thisWeek, float salary) { thisWeek = 42; cout << "\n\nIn the Earnings() function,"; cout << "\n\tWeekly Hours = " << thisWeek; cout << "\n\tSalary = " << salary; cout << "\n\tWeekly Salary= " << thisWeek * Salary; }
If you test the program with a weekly hours
value of 35.50 and a salary of 8.50, you would notice that the weekly
salary is different inside of the Earnings() function but is kept the
same in main(), before and after the Earnings() function. As an example
of passing an argument by reference, you could modify the declaration of
the Earnings() function inside of the main() function as follows:
void Earnings(float &h, float r);
If you want a calling function to modify the
value of an argument, you should supply its reference and not its value.
You could change the function as follows:
void Earnings(float &thisWeek, float salary) { thisWeek = 42; cout << "\n\nIn the Earnings() function,"; cout << "\n\tWeekly Hours = " << thisWeek; cout << "\n\tSalary = " << salary; cout << "\n\tWeekly Salary= " << thisWeek * Salary; } |
Default Arguments
|
Whenever a function takes an argument, that
argument is required. If the calling function does not provide the
(required) argument, the compiler would throw an error.
Imagine you write a function that will be used
to calculate the final price of an item after discount. The function
would need the discount rate in order to perform the calculation. Such a
function could look like this:
double CalculateNetPrice(double discountRate) { double OrigPrice; cout << "Please enter the original price: "; cin >> origPrice; return origPrice - (origPrice * discountRate / 100); }
Since this function expects an argument, if you do not supply it, the following program would not
compile:
#include <iostream> using namespace std; double CalculateNetPrice(double discountRate) { double origPrice; cout << "Please enter the original price: "; cin >> origPrice; return origPrice - (origPrice * discountRate / 100); } int main() { double finalPrice; double discount = 15; // That is 25% = 25 finalPrice = CalculateNetPrice(discount); cout << "\nFinal Price = " << finalPrice << "\n\n"; return 0; }
Most of the time, a function such as ours would use the same discount
rate over and over again. Therefore, instead of supplying an argument
all the time, C++ allows you to define an argument whose value would be
used whenever the function is not provided with the argument.
To give a default value to an argument, when
declaring the function, type the name of the argument followed by the
assignment operator “=”, followed by the default value. The
CalculateNetPrice() function, with a default value, could be defined as:
#include <iostream> using namespace std; double CalculateNetPrice(double discountRate = 25) { double origPrice; cout << "Please enter the original price: "; cin >> origPrice; return origPrice - (origPrice * discountRate / 100); } int main() { double finalPrice; finalPrice = calculateNetPrice(); cout << "\nFinal Price = " << finalPrice << "\n\n"; return 0; }
If a function takes more than one argument,
you can provide a default argument for each and select which ones would
have default values. If you want all arguments to have default values,
when defining the function, type each name followed by = followed by the
desired value. Here is an example:
#include <iostream> using namespace std; double CalculateNetPrice(double tax = 5.75, double discount = 25, double origPrice = 245.55) { double discountValue = origPrice * discount / 100; double taxValue = tax / 100; double netPrice = origPrice - discountValue + taxValue; cout << "Original Price: $" << origPrice << endl; cout << "Discount Rate: " << discount << "%" << endl; cout << "Tax Amount: $" << tax << endl; return netPrice; } int main() { double finalPrice; finalPrice = CalculateNetPrice(); cout << "Final Price: $" << finalPrice << "\n\n"; return 0; }
Here is the result produced:
Original Price: $245.55 Discount Rate: 25% Tax Amount: $5.75 Final Price: $184.22 Press any key to continue...
If a function receives more than one argument and you would like to provide
default values for those parameters, the order of appearance of the arguments is very important.
|
Techniques of Using Functions
|
Function Overloading
|
A C++ program involves a great deal of names
that represent variables and functions of various kinds. The compiler
does not allow two variables to have the same name in the same function.
Although two functions should have unique names in the same program,
C++ allows you to use the same name for different functions of the same
program following certain rules. The ability to have various functions
with the same name in the same program is called function overloading.
The most important rule about function overloading is to make sure that
each one of these functions has a different number or different
type(s) of arguments.
|
The moment of inertia is the ability of of a beam to resist bending. It
is calculated with regard to the cross section of the beam. Because it
depends on the type of section of the beam, its calculation also depends
on the type of section of the beam. In this exercise, we will review
different formulas used to calculate the moment of inertia. Since this
exercise is for demonstration purposes, you do not need to be a Science
Engineering major to understand it.
|
Here are the formulas to calculate the moment of inertia for a semi-circle:
|
#include <iostream> using namespace std; // Rectangle double MomentOfInertia(double b, double h) { return b * h * h * h / 3; } // Semi-Circle double MomentOfInertia(double R) { const double PI = 3.14159; return R * R * R * R * PI/ 8; } int main() { double base, height, radius; cout << "Enter the dimensions of the Rectangle\n"; cout << "Base: "; cin >> base; cout << "Height: "; cin >> height; cout << "\nMoment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(base, height) << "mm"; cout << "\n\nEnter the radius: "; cin >> radius; cout << "Moment of inertia of a semi-circle with regard to the X axis: "; cout << "I = " << MomentOfInertia(radius) << "mm\n\n"; return 0; } |
As you can see, the rectangle and the triangle are using the same dimension types. This
means that we can provide only the same kinds of arguments, the base and the height, to calculate the moment of inertia.
This also means C++ will not allow us to write two functions that have the same
name, the same number of arguments, and the same types of arguments because that
would violate the rule of function overloading.
In order to overload the MomentOfInertia()
function, we will add an argument that will never be used; this argument
will serve only as a “witness” to set the difference between both
versions of the function. This “witness” argument can be anything: an
integer, a character, a string, a float, etc. For our example, we will
make it a simple integer. To use the version applied to the triangle, we
will provide this argument to overload the
MomentOfInertia() function. When called with only two arguments,
the rectangle version will apply.
Here is an example that calculates the moment of inertia with regard to the X axis, overloading the MomentOfInertia function as follows: |
#include <iostream> using namespace std; // Rectangle double MomentOfInertia(double b, double h) { return b * h * h * h / 3; } // Semi-Circle double MomentOfInertia(double R) { const double PI = 3.14159; return R * R * R * R * PI/ 8; } // Triangle double MomentOfInertia(double b, double h, int) { return b * h * h * h / 12; } int main() { double base = 7.74, height = 14.38, radius = 12.42; cout << "Rectangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(base, height) << "mm\n\n"; cout << "Semi-Circle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(radius) << "mm\n\n"; cout << "Enter the dimensions of the triangle\n"; cout << "Base: "; cin >> base; cout << "Height: "; cin >> height; cout << "\nTriangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(base, height, 1) << "mm\n\n"; return 0; } |
Inline Functions
|
When you call a function B() from function A(),
function A() sends a request and must get to Function B(). This is
sometimes cumbersome for long functions. Whenever your program includes a
small function, C++ allows you to include such a function where it is
being called. When function B() calls function A(), instead of sending a
request to function A(), the compiler would include a copy of function A()
into function B() where it is being called. Such a function (function A())
is qualified inline.
To create a function as inline, use the inline keyword when declaring the function as well as when defining it. Here is an example that makes use of an inline function: |
#include <iostream> using namespace std; inline void Area(float Side) { cout << "The area of the square is " << Side * Side; } int main() { float s; cout << "Enter the side of the square: "; cin >> s; Area(s); return 0; }
Here is an example of running the program:
Enter the side of the square: 14.55 The area of the square is 211.702
You can also use the keyword on an inline function. To
declare a function as inline and, type both words at the beginning of the
declaration. The following program requests the hourly salary from the
user. Then it calculates the periodic earnings:
|
#include <iostream> using namespace std; void inline RequestSalary(double& h); inline double Daily(double h); double inline Weekly(double h); inline double BiWeekly(double h); double inline Monthly(double h); double inline Yearly(double h); int main() { double HourlySalary; cout << "This program allows you to evaluate your salary " << "for different periods\n"; RequestSalary(HourlySalary); cout << "\nBased on the hourly rate you supplied, here are your " << "periodic earnings"; cout << "\n\tHourly: $" << HourlySalary; cout << "\n\tDaily: $" << Daily(HourlySalary); cout << "\n\tWeekly: $" << Weekly(HourlySalary); cout << "\n\tBi-Weekly: $" << BiWeekly(HourlySalary); cout << "\n\tMonthly: $" << Monthly(HourlySalary); cout << "\n\tYearly: $" << Yearly(HourlySalary); cout << "\n\n"; return 0; } void inline RequestSalary(double& x) { cout << "Enter your hourly salary: $"; cin >> x; } inline double Daily(double x) { return x * 8; } double inline Weekly(double x) { return Daily(x) * 5; } inline double BiWeekly(double x) { return Weekly(x) * 2; } double inline Monthly(double x) { return Weekly(x) * 4; } double inline Yearly(double h) { return Monthly(h) * 12; }
Here is an example of running the program:
This program allows you to evaluate your salary for different periods Enter your hourly salary: $15.55 Based on the hourly rate you supplied, here are your periodic earnings Hourly: $15.55 Daily: $124.4 Weekly: $622 Bi-Weekly: $1244 Monthly: $2488 Yearly: $29856
No comments:
Post a Comment