Objective #1: Learn how to build structured programs that are divided into
functions.
Objective #2: Understand what is meant by the phrase "scope of
variables."
- Variables can be 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 your program and functions' autonomy and encapsulation,
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. The scope of a global variable is considered to be wider than the more narrow scope of a local variable.
- 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.
(numOfTimes isn't really a variable. It is
a parameter technically. See Objective #3 below for more details on parameters.)
Objective #3: Understand how data is passed to functions.
- Data is passed to functions as arguments
and parameters.
When a function is "called" by the main function (or another function),
one or more arguments are passed to the function. On the receiving end, the
function accepts these arguments (technically, as parameters). The variable
names of the arguments (from the "calling" function) do not have
to be the same as the names of the parameters (in the "called"
function.) But, the datatypes of the arguments and the parameters must match
exactly. The list of parameters in the order that they are specified in the
function prototype and function header (see below) is called the function's
"parameter list".
- The values that are sent by the calling function to the called function
are known as arguments or actual parameters. On the other end, in the called
function, those values are stored in formal parameters. The number of actual
parameters (or arguments) must match the number of formal parameters or a
compiler error will result (unless default values were included). Also, the
order of the actual parameters with regard to data type must exactly match
the order of the formal parameters with regard to data type or a compiler
error will result.
- Within the function definition itself, we distinguish between its first
line and the rest of the function. The first line is called the function header
and will look very similar to the function's prototype except for a semicolon
at the end. The rest of the function is enclosed in braces and is called the
function body. Function definitions are commonly placed below the main function
in C++. Function prototypes, by the way, are commonly placed before the main
function.
- It is good style to include pre- and postconditions with functions that
you write though this is not required by our class Coding Standards. Preconditions
are conditions that must be true for the function to work properly. Postconditions
are conditions that are guaranteed to be true after the function has executed.
- Local variables may be declared and initialized within the body of a function.
However, these variables cannot be accessed anywhere else in the C++ program
outside of that function since they have local scope.
- Many functions need to "return" a value with a return statement.
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. 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. The keyword void is used
as the return type if a function does not have a return
statement or need to return a value to the calling function.
- If a function does not need any values in order to operate and perform its
function, it will have an empty parameter list such as in:
void displayTitleOfProgram( )
{
cout << "Minich's Sample C++ Program"
<< endl;
}// end of displayTitleOfProgram
where no arguments needed to be sent to the function for it to fulfill its
purpose.
- There are mainly two ways to pass data as arguments to functions in C++.
You can pass data by value or by reference. We will not be studying how to pass by reference in this course but it is explained below anyway.
- passing by value
is the preferred method. 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.
- passing by reference is
to be used when you want a single function to actually and permanently
change the values of one or more variables. This method is dangerous
but sometimes more efficient since it allows you to affect and permanently
change the values of arguments in your calling function. You must use
an ampersand (&) before the parameter
names in the function definition (the first line of the actual called
function) to pass variable by reference.
Objective #4: 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. 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. In fact, you do not even have to know exactly how they work. You
do have to know how many arguments to send to the functions and what datatypes
to use for those functions. For example, there are many mathematical library
functions that can be used in your program if you "include" the
cmath
header file at the top of your program. Similarly, the ctype
header file may be useful as well.
- 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 many library functions in C++. You should be familiar with the library functions sqrt, pow, abs, ceil, floor , and rand. You must add #include <cmath> to the top of your program if you use the functions sqrt, pow, ceil, & floor. You should 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 absolute value of an integer. The statement
cout << abs(-9) << endl;
displays the positive value 9.
- The ceil function returns the next integer greater than it's parameter. The statement
cout << ceil(9.2) << endl;
displays the value 10. While
cout << ceil(-3.9) << endl;
displays the value -3.
- The floor function returns the next smallest integer than it's parameter. The statement
cout << floor(9.9) << endl;
displays the value 9. While
cout << floor(-3.9) << endl;
displays the value -4.
- The rand function is used to generate a random value as in
cout << "A random number is " << rand() << endl;
- The rand, srand,
and randomize library functions are useful
for generating pseudorandom numbers. The rand function produces a random number
between or equal to 0 and RAND_MAX, where
RAND_MAX is defined in the cstdlib
header file for your particular compiler and platform. The srand
function sets a seed value for rand so that
rand will not always produce the same random numbers every time the C++ program
is executed. Our compiler, Visual C++, allows you to use the statement
randomize( );
instead of
srand(time(NULL));
But you must include stdlib and time
library functions, in order to use randomize in this way.
- You may have to manipulate the pseudorandom numbers generated by rand within
a program using a technique called scaling. For example, the expression
int(rand( ) / RAND_MAX * 100)
will generate a random integer between 0 and 100. The general expression
low + rand( ) % (high + 1 - low)
will genate a random integer between low and high.