We will not be covering section 4.6 on pp. 228-236. From Ch. 5 we will only be covering section 1 on pp. 248-255.
Objective #1: Be able to build structured programs that are divided
into functions.
Objective #2: Understand what is meant by the phrase "scope
of variables."
- Variables are either global
or local in nature. Global
variables are ones that are declared outside and above
the main function. They can be used in any function throughout
the program. It is not wise to use global variables any more than you
have to. One small error (for example, miscalculating a value) could
lead to multiple, hard-to-find errors in large programs. Local variables
are ones that are declared inside of a function, including main. They
cannot be used or referred to in other functions.
- In order to strengthen a function's reusability,
you should avoid the use of global variables and try to use local
variables instead.
- The scope
of a variable is the area in which it can be legally referenced. A global
variable's scope is the whole program. A local variable's scope is the
function in which it is declared.
- In the example program above (with the function printMyName), the
variable userInput is a local variable which belongs to the main function.
The variable i is a local variable to the function printMyName. The parameter numOfTimes isn't really considered to be a variable. It is a parameter technically. See the notes below for more details on parameters.
Objective #3: Be able to use functions in a C++ program.
- A function must be given a valid identifier as a name. A good name
for a function that computes sales tax would be computeSalesTax. Like
variables, I prefer that you name functions by capitalizing multiple words except for the first letter of the identifier.
- The first line of a function is called the function header.
Before the name of the function you must specify a "return type."
The return type is the data type of the value that is returned by the
function to the calling function (usually the main function in this
CMPSC 101 course).
- After the name of the function in the function header, you must include
a parameter list. The parameter list is a pair of parentheses
with 0 or more parameters listed. Each parameter is passed to the function
from the calling function. Immediately preceding each parameter, you
must identify the data type of that parameter. If the function does
not return any value, you must type the word void as the return type.
An example of a function header is:
double computeTax(double myPrice, double myTaxRate)
where the name of the function is computeTax, the return type is double,
and the passed parameters are myPrice and myTaxRate.
- Following the function header comes the function body, which
is enclosed in a pair of curly braces. If the function is not a void
function, there must be a return statement at the end of the function.
The return statement returns a computed value to the calling function.
Example:
double computeTax(double myPrice, double
myTaxRate)
{
return (myPrice * myTaxRate);
}// end of computeTax
In the example the expression (myPrice * myTaxRate)
is first computed and the resulting value is returned to the calling
function. Note that the parentheses in around the expression in the
return statement are optional. However,
you could also use a local variable to first store the computed amount
of tax and then return the same value as in:
double computeTax(double myPrice, double myTaxRate)
{
double result = 0.0;
result = myPrice * myTaxRate;
return result;
}// end of computeTax
Some would argue that this function is slightly more readable however
it does require an additional 8 bytes of memory for the local variable
result. Since result is declared within
the function, it cannot be used or referenced in any other function
of the C++ program.
- You should avoid using cin or cout
statements within functions. Unless the whole purpose of a function
is to obtain (and or validate) a user's input, you should not use a
cin statement within a function (besides
main). Unless the whole purpose of
a function is to display something such as a menu, you should avoid
using a cout statement within a function
(besides main). If you did create a
function with the sole purpose of displaying a menu, it would likely
be a void function.
Objective #4: Understand how data is passed to functions.
- Data is passed to functions as parameters
(sometimes referred to as actual
parameters or arguments). When a function is "called"
by the main function (or another function), one or more parameters may be
passed to the function. On the receiving end, the function accepts these
parameters (technically, here they are called formal parameters). The variable names of
the parameters (that is, actual parameters) from the "calling"
function do not have to be the same as the names of the formal parameters
in the "called" function. But, the datatypes of the arguments
and the parameters should match exactly. An error could occur if the
data types do not match.
- We type return 0; as the last statement
in the main functions of all the programs
that we write in this C++ course. This returns a message (of "0")
to the operating system indicating that our C++ program ran successfully.
A returned nonzero value is often used by programmers to indicate that
an error occurred during the program's execution.
- Often, though, you want your function to return a computed value to
the calling function. This value is used in the exact statement that
the function was called. For example,
fahrenheit
= celsiusToFahrenheit(celsius);
sends the argument, celsius, to the function, celsiusToFahrenheit,
where it is used to determine the equivalent Fahrenheit temperature.
Then, the final value is returned from within the function to the
main function where it is assigned
to the fahrenheit variable.
- However, in this call statement, instead of storing the value returned by the function in a variable, the returned value is being displayed using cout
cout << celsiusToFahrenheit(celsius) << endl;
- Passing by value
is the preferred method of passing data to a function. You simply use
a variable name, an actual numeric literal, or an expression in the
parentheses of the call statement. This method is the safest because
it does not actually change the value of the argument in the calling
function.
In the example below, the argument named price
is passed by value to the function addTax.
#include <iostream>
using namespace std;
double addTax(double);
int main()
{
double price = 10.00;
double finalPrice = 0.0;
finalPrice = addTax(price);
cout << "The final price with tax is "
<< finalPrice << endl;
return 0;
}// end of main
double addTax(double initialPrice)
{
return (initialPrice + initialPrice * 0.06);
}// end of addTax
- Passing by reference
is to be used when you want the function to actually and permanently
change the values of one or more variables. You must use an ampersand
(&) before the formal parameter names in the function header
(the first line of the function definition) to denote passing
by reference. We will not be studying passing by reference in this CMPSC 101 course. Although, you can read more about passing by reference in Chapter 5.
Objective #5: Be able to use void
functions when appropriate.
- A void function is
simply a function that does not return a value. The function header
and the function prototype for a void function begins with the word
void.
- Often a void function simply consists of cout statements.
- An example of a void function might be one that is used to print a menu such as:
void printMenu()
{
cout << "1. apples" << endl;
cout << "2. bananas" << endl;
cout << "3. carrots" << endl;
cout << "4. exit" << endl;
}// end of printMenu
Notice that a void function does not have a return statement. Therefore the keyword void is typed at the beginning of the function header as the return type of the function. It would be efficient to use this function in a program that must display a menu many times. By calling the function over and over again, you are cutting down on the amount of code (i.e. cout statements) that must be placed in the main function. To call a void function you would use the call statement that is found in the short program below
#include <iostream>
using namespace std;
int main()
{
int userChoice = 0;
while (userChoice != 4)
{
printMenu();
cout << "Enter choice: ";
cin >> userChoice;
}
return 0;
}// end of main
Objective #6: Learn how to use the library functions that are included with the compiler.
- There are many functions available to C++ programmers which were written
by other programmers. These functions are known as library functions (and sometimes called predefined functions.) You can use the #include
compiler directive at the top of your program to take advantage of these
functions. The source code for those functions does not need to be included
within your program.
- There are a number of library functions listed on p. 185. You should be familiar with how to use the library functions sqrt, pow, abs, fabs, ceil, floor , and rand. You must add #include <cmath> to the top of your program if you use the functions sqrt, pow, fabs, ceil, & floor. You must add #include <cstdlib> to the top of your program if you use the functions abs and rand.
- The sqrt function can be used to compute a square root. The following statement displays the square root of 13:
cout << sqrt(13) << endl;
- The pow function can be used to calculate a number to a power. The statement
cout << pow(3, 2) << endl;
displays the value 9.
- The abs function is used to calculate the absoute value of an integer. The statement
cout << abs(-9) << endl;
displays the positive value 9.
- The fabs function is used to calculate the absolute value of a floating-point value. The statement
cout << fabs(-9.2) << endl;
displays the positive value 9.2.
- The rand function is used to generate a random value as in
cout << "A random number is " << rand() << endl;
We will not be studying the material on pp.
151-165 of Ch. 4 in this course.
Objective #7: Understand how to pass by reference.
-
passing by reference
is to be used when you want the function to actually and permanently
change the values of one or more variables. This method is dangerous
but beneficial sometimes since it allows you to affect the values
of arguments in your calling function. You would purposefully pass
by reference if you want to return 2 or more values to the calling
function. Since it is not possible in C++ to execute two return
statements within a function and since it is not possible to return
two values in the same return statement
(i.e. return myResult, myOtherResult
is illegal), passing by reference can allow you to modify two or more
variables in the calling function (i.e. main). Also, if you need to
pass a really large variable or object, it saves memory to pass by
reference. Since a copy of the variable is not being made when you
pass by reference, less memory overhead is required. For int,
double, and char
variables, passing by reference to save memory is not really necessary.
However, if you were to pass a large "object" such as a
piece of clipart or a whole file, you would intentionally pass by
reference.
You must use an ampersand (&) before the formal parameter names
in the function header to denote passing by reference.
In the example below, the argument named price
is passed by reference to the function addTax.
#include <iostream>
using namespace std;
void addTax(double & incomingPrice);
int main()
{
double price = 10.00;
addTax(price);
cout << "The final price with tax is
" << price << endl;
return 0;
}// end of main
void addTax(double & incomingPrice)
{
incomingPrice = incomingPrice + incomingPrice *
0.06;
}// end of addTax