Download c++ programming -functions and more Lecture notes Programming Languages in PDF only on Docsity!
User-Defined Functions
using functions in a program greatly enhances the program’s
readability because it reduces the complexity of the function mmaaiinn. Also, once you write
and properly debug a function, you can use it in the program (or different programs)
again and again without having to rewrite the same code repeatedly.
Because C++ does not provide every function that you will ever need and designers
cannot possibly know a user’s specific needs, you must learn to write your own
functions.
User-defined functions in C++ are classified into two categories:
- Value-returning functions—functions that have a return type. These
functions return a value of a specific data type using the return
statement, which we will explain shortly.
- Void functions—functions that do not have a return type. These
functions do not use a return statement to return a value.
The remainder of this chapter discusses value-returning functions. Many of the concepts
discussed in regard to value-returning functions also apply to void functions. Chapter 7
describes void functions.
Value-Returning Functions
The previous section introduced some predefined C++ functions such as ppooww, aabbss,
iisslloowweerr, and ttoouuppppeerr. These are examples of value-returning functions. To use these
functions in your programs, you must know the name of the header file that contains the
functions’ specification. You need to include this header file in your program using the
include statement and know the following items:
1. The name of the function
2. The number of parameters, if any
3. The data type of each parameter
4. The data type of the value computed (that is, the value returned) by the
function, called the type of the function
Because the value returned by a value-returning function is unique, the natural
thing for you to do is to use the value in one of three ways:
- Save the value for further calculation.
- Use the value in some calculation.
- Print the value.
324 | Chapter 6: User-Defined Functions I
This suggests that a value-returning function is used:
- In an assignment statement.
- As a parameter in a function call.
- In an output statement.
That is, a value-returning function is used (called) in an expression.
Before we look at the syntax of a user-defined, value-returning function, let us consider
the things associated with such functions. In addition to the four properties described
previously, one more thing is associated with functions (both value-returning and void):
5. The code required to accomplish the task
The first four properties form what is called the heading of the function (also called the
function header); the fifth property is called the body of the function. Together, these
five properties form what is called the definition of the function. For example, for the
function aabbss, the heading might look like:
int aabbss((int nnuummbbeerr))
Similarly, the function aabbss might have the following definition:
int aabbss((int nnuummbbeerr)) {{ if ((nnuummbbeerr << 00)) nnuummbbeerr == --nnuummbbeerr;;
return nnuummbbeerr;; }}
The variable declared in the heading of the function aabbss is called the formal parameter
of the function aabbss. Thus, the formal parameter of aabbss is nnuummbbeerr.
The program in Example 6-1 contains several statements that use the function ppooww. That
is, in C++ terminology, the function ppooww is called several times. Later in this chapter, we
discuss what happens when a function is called.
Suppose that the heading of the function ppooww is:
double ppooww((double bbaassee,, double eexxppoonneenntt))
From the heading of the function ppooww, it follows that the formal parameters of ppooww are
bbaassee and eexxppoonneenntt. Consider the following statements:
double uu == 22..55;; double vv == 33..00;; double xx,, yy;;
xx == ppooww((uu,, vv));; //Line 1 yy == ppooww((22..00,, 33..22)) ++ 55..11;; //Line 2 ccoouutt <<<< uu <<<< "" ttoo tthhee ppoowweerr ooff 77 == "" <<<< ppooww((uu,, 77)) <<<< eennddll;; //Line 3
6
Value-Returning Functions | 325
Syntax: Actual Parameter List
The syntax of the actual parameter list is:
eexxpprreessssiioonn oorr vvaarriiaabbllee,, eexxpprreessssiioonn oorr vvaarriiaabbllee,, ......
(In this syntax, eexxpprreessssiioonn can be a single constant value.) Thus, to call a value-
returning function, you use its name, with the actual parameters (if any) in parentheses.
A function’s formal parameter list can be empty. However, if the formal parameter list is
empty, the parentheses are still needed. The function heading of the value-returning
function thus takes, if the formal parameter list is empty, the following form:
ffuunnccttiioonnTTyyppee ffuunnccttiioonnNNaammee(())
If the formal parameter list of a value-returning function is empty, the actual parameter is
also empty in a function call. In this case (that is, an empty formal parameter list), in a
function call, the empty parentheses are still needed. Thus, a call to a value-returning
function with an empty formal parameter list is:
ffuunnccttiioonnNNaammee(())
In a function call, the number of actual parameters, together with their data types, must
match with the formal parameters in the order given. That is, actual and formal para-
meters have a one-to-one correspondence. (Chapter 7 discusses functions with default
parameters.)
As stated previously, a value-returning function is called in an expression. The expression
can be part of either an assignment statement or an output statement, or a parameter in a
function call. A function call in a program causes the body of the called function to
execute.
return Statement
Once a value-returning function computes the value, the function returns this value via
the return statement. In other words, it passes this value outside the function via the
return statement.
Syntax: return Statement
The return statement has the following syntax:
return eexxpprr;;
in which eexxpprr is a variable, constant value, or expression. The eexxpprr is evaluated, and its
value is returned. The data type of the value that eexxpprr computes must match the
function type.
6
Value-Returning Functions | 327
In C++, return is a reserved word.
When a return statement executes in a function, the function immediately terminates
and the control goes back to the caller. Moreover, the function call statement is replaced
by the value returned by the return statement. When a return statement executes in
the function mmaaiinn, the program terminates.
To put the ideas in this discussion to work, let us write a function that determines the
larger of two numbers. Because the function compares two numbers, it follows that this
function has two parameters and that both parameters are numbers. Let us assume that the
data type of these numbers is floating-point (decimal)—say, double. Because the larger
number is of type double, the function’s data type is also double. Let us name this
function llaarrggeerr. The only thing you need to complete this function is the body of the
function. Thus, following the syntax of a function, you can write this function as follows:
double llaarrggeerr((double xx,, double yy)) {{ double mmaaxx;;
if ((xx >>== yy)) mmaaxx == xx;; else mmaaxx == yy;;
return mmaaxx;; }}
Note that the function llaarrggeerr requires that you use an additional variable mmaaxx (called a
local declaration, in which mmaaxx is a variable local to the function llaarrggeerr). Figure 6-
describes various parts of the function llaarrggeerr.
{
max = x;
max = Y;
else
}
Function return type
Function name
Formal parameters
Formal parameters list
Function return value
Local variable Function body
Function heading double^ larger(^ double^ x,^ doubley)
max;
max;
return
double
if (x >= y)
FIGURE 6-1 Various parts of the function larger
328 | Chapter 6: User-Defined Functions I
E X A M P L E 6 - 2
Now that the function llaarrggeerr is written, the following C++ code illustrates how to use it.
double oonnee == 1 13 3..0 00 0;; double ttwwoo == 3 36 6..5 53 3;; double mmaaxxNNuumm;;
Consider the following statements:
ccoouutt <<<< ""TThhee llaarrggeerr ooff 55 aanndd 66 iiss "" <<<< llaarrggeerr((55,, 66)) <<<< eennddll;; //Line 1
ccoouutt <<<< ""TThhee llaarrggeerr ooff "" <<<< oonnee <<<< "" aanndd "" <<<< ttwwoo <<<< "" iiss "" <<<< llaarrggeerr((oonnee,, ttwwoo)) <<<< eennddll;; //Line 2
ccoouutt <<<< ""TThhee llaarrggeerr ooff "" <<<< oonnee <<<< "" aanndd 2 29 9 iiss "" <<<< llaarrggeerr((oonnee,, 2 29 9)) <<<< eennddll;; //Line 3
mmaaxxNNuumm == llaarrggeerr((3 38 8..4 45 5,, 5 56 6..7 78 8));; //Line 4
- The expression llaarrggeerr((55,, 66)) in Line 1 is a function call, and 55 and 66
are actual parameters. When the expression llaarrggeerr((55,, 66)) executes, 55 is
copied into xx, and 66 is copied into yy. Therefore, the statement in Line 1
outputs the larger of 55 and 66.
- The expression llaarrggeerr((oonnee,, ttwwoo)) in Line 2 is a function call. Here, oonnee
and ttwwoo are actual parameters. When the expression llaarrggeerr((oonnee,, ttwwoo))
executes, the value of oonnee is copied into xx, and the value of ttwwoo is copied
into yy. Therefore, the statement in Line 2 outputs the larger of oonnee and ttwwoo.
- The expression llaarrggeerr((oonnee,, 2 29 9)) in Line 3 is also a function call. When
the expression llaarrggeerr((oonnee,, 2 29 9)) executes, the value of oonnee is copied
into xx, and 2299 is copied into yy. Therefore, the statement in Line 3
outputs the larger of oonnee and 2299.
- The expression llaarrggeerr((3 38 8..4 45 5,, 5 56 6..7 78 8)) in Line 4 is a function call. In this
call, the actual parameters are 338 8..4 455 and 556 6..7 788. In this statement, the value
returned by the function llaarrggeerr is assigned to the variable mmaaxxNNuumm.
In a function call, you specify only the actual parameter, not its data type. For example, in Example 6-2, the statements in Lines 1, 2, 3, and 4 show how to call the function llaarrggeerr with the actual parameters. However, the following statements contain incorrect
calls to the function llaarrggeerr and would result in syntax errors. (Assume that all variables
are properly declared.)
xx == llaarrggeerr((int oonnee,, 2 29 9));; //illegal yy == llaarrggeerr((int oonnee,, int 229 9));; //illegal ccoouutt <<<< llaarrggeerr((int oonnee,, int ttwwoo));; //illegal
330 | Chapter 6: User-Defined Functions I
Once a function is written, you can use it anywhere in the program. The function
llaarrggeerr compares two numbers and returns the larger of the two. Let us now write
another function that uses this function to determine the largest of three numbers. We
call this function ccoommppaarreeTThhrreeee.
double ccoommppaarreeTThhrreeee((double xx,, double yy,, double zz))
{{
return llaarrggeerr((xx,, llaarrggeerr((yy,, zz))));;
}}
In the function heading, xx, yy, and zz are formal parameters.
Let us take a look at the expression:
llaarrggeerr((xx,, llaarrggeerr((yy,, zz))))
in the definition of the function ccoommppaarreeTThhrreeee. This expression has two calls to the
function llaarrggeerr. The actual parameters to the outer call are xx and llaarrggeerr((yy,, zz));
the actual parameters to the inner call are yy and zz. It follows that, first, the expression
llaarrggeerr((yy,, zz)) is evaluated; that is, the inner call executes first, which gives the larger of yy
and zz. Suppose that llaarrggeerr((yy,, zz)) evaluates to, say, tt. (Notice that tt is either yy or zz.)
Next, the outer call determines the larger of xx and tt. Finally, the return statement returns
the largest number. It thus follows that to execute a function call, the parameters are evaluated
first. For example, the actual parameter llaarrggeerr((yy,, zz)) of the outer call evaluates first.
Note that the function llaarrggeerr is much more general purpose than the function
ccoommppaarreeTThhrreeee. Here, we are merely illustrating that once you have written a function,
you can use it to write other functions. Later in this chapter, we will show how to use the
function llaarrggeerr to determine the largest number from a set of numbers.
Function Prototype
Now that you have some idea of how to write and use functions in a program, the next
question relates to the order in which user-defined functions should appear in a program.
For example, do you place the function llaarrggeerr before or after the function mmaaiinn?
Should llaarrggeerr be placed before ccoommppaarreeTThhrreeee or after it? Following the rule that you
must declare an identifier before you can use it and knowing that the function mmaaiinn uses
the identifier llaarrggeerr, logically you must place llaarrggeerr before mmaaiinn.
In reality, C++ programmers customarily place the function mmaaiinn before all other user-
defined functions. However, this organization could produce a compilation error because
functions are compiled in the order in which they appear in the program. For example, if
the function mmaaiinn is placed before the function llaarrggeerr, the identifier llaarrggeerr is
undefined when the function mmaaiinn is compiled. To work around this problem of
undeclared identifiers, we place function prototypes before any function definition
(including the definition of mmaaiinn).
Function Prototype: The function heading without the body of the function.
6
Value-Returning Functions | 331
6
ccoouutt <<<< ""LLiinnee 77:: TThhee llaarrggeesstt ooff 4 43 3..4 48 8,, 3 34 4..0 00 0,, "" <<<< ""aanndd 1 12 2..6 65 5 iiss "" <<<< ccoommppaarreeTThhrreeee((4 43 3..4 48 8,, 3 34 4..0 00 0,, 1 12 2..6 65 5)) <<<< eennddll;; //Line 7
return 0 0;; }}
double llaarrggeerr((double xx,, double yy)) {{ double mmaaxx;;
if ((xx >>== yy)) mmaaxx == xx;; else mmaaxx == yy;;
return mmaaxx;; }}
double ccoommppaarreeTThhrreeee ((double xx,, double yy,, double zz)) {{ return llaarrggeerr((xx,, llaarrggeerr((yy,, zz))));; }}
Sample Run: In this sample run, the user input is shaded.
LLiinnee 22:: TThhee llaarrggeerr ooff 55 aanndd 1 10 0 iiss 1 100 LLiinnee 33:: EEnntteerr ttwwoo nnuummbbeerrss:: 2 25 5..66 7 73 3..8 855
LLiinnee 66:: TThhee llaarrggeerr ooff 2 25 5..66 aanndd 7 73 3..8 85 5 iiss 7 73 3..8 855 LLiinnee 77:: TThhee llaarrggeesstt ooff 4 43 3..4 48 8,, 3 34 4..0 00 0,, aanndd 1 12 2..6 65 5 iiss 4 43 3..4 488
In the previous program, the function prototypes of the functions llaarrggeerr and
ccoommppaarreeTThhrreeee appear before their function definitions. Therefore, the definition of
the functions llaarrggeerr and ccoommppaarreeTThhrreeee can appear in any order.
Value-Returning Functions: Some Peculiarity
A value-returning function must return a value. Consider the following function, sseeccrreett,
that takes as a parameter an int value. If the value of the parameter, xx, is greater than 55 , it
returns twice the value of xx; otherwise, the value of xx remains unchanged.
int sseeccrreett((int xx)) {{
if ((xx >> 55)) //Line 1 return 2 2 ** xx;; //Line 2 }}
Because this is a value-returning function of type int, it must return a value of type int.
Suppose the value of xx is 1100. Then the expression xx >> 5 5 in Line 1 evaluates to true. So
the return statement in Line 2 returns the value 2200. Now suppose that xx is 33. The
Value-Returning Functions | 333
expression xx >> 5 5 in Line 1 now evaluates to false. The if statement therefore fails, and
the return statement in Line 2 does not execute. However, there are no more statements
to be executed in the body of the function. In this case, the function returns a strange
value. It thus follows that if the value of xx is less than or equal to 55 , the function does not
contain any valid return statements to return the value of xx.
A correct definition of the function sseeccrreett is:
int sseeccrreett((int xx)) {{
if ((xx >> 55)) //Line 1 return 2 2 ** xx;; //Line 2
return xx;; //Line 3 }}
Here, if the value of xx is less than or equal to 55 , the return statement in Line 3
executes, which returns the value of xx. On the other hand, if the value of xx is, say
1100 , the return statement in Line 2 executes, which returns the value 2200 and also
terminates the function.
Recall that in a value-returning function, the return statement returns the value.
Consider the following return statement:
return xx,, yy;; //only the value of y will be returned
This is a legal return statement. You might think that this return statement is
returning the values of xx and yy. However, this is not the case. Remember, a return
statement returns only one value, even if the return statement contains more
than one expression. If a return statement contains more than one expression, only
the value of the last expression is returned. Therefore, in the case of the above return
statement, the value of yy is returned. The following program further illustrates this
concept.
// This program illustrates that a value-returning function // returns only one value, even if the return statement // contains more than one expression.
#include <>
using namespace ssttdd;;
int ffuunnccRReett11(());; int ffuunnccRReett22((int zz));;
int mmaaiinn(()) {{
int nnuumm == 44;;
ccoouutt <<<< ""LLiinnee 11:: TThhee vvaalluuee rreettuurrnneedd bbyy ffuunnccRReett11:: "" <<<< ffuunnccRReett11(()) <<<< eennddll;; // Line 1
334 | Chapter 6: User-Defined Functions I
you learned how to use value-returning functions. In this chapter, you will
explore user-defined functions in general and, in particular, those C++ functions that do
not have a data type, called void functions.
Void Functions
Void functions and value-returning functions have similar structures. Both have a
heading and a body. Like value-returning functions, you can place user-defined void
functions either before or after the function mmaaiinn. However, the program execution
always begins with the first statement in the function mmaaiinn. If you place user-defined
void functions after the function mmaaiinn, you should place the function prototype
before the function mmaaiinn. A void function does not have a data type. Therefore,
ffuunnccttiioonnTTyyppee—that is, the return type—in the heading part and the return state-
ment in the body of the void functions are meaningless. However, in a void
function, you can use the return statement without any value; it is typically used
to exit the function early. Like value-returning functions, void functions may or may
not have formal parameters.
Because void functions do not have a data type, they are not used (called) in an
expression. A call to a void function is a stand-alone statement. Thus, to call a void
function, you use the function name together with the actual parameters (if any) in a
stand-alone statement. Before giving examples of void functions, next we give the syntax
of a void function.
FUNCTION DEFINITION
The function definition of void functions with parameters has the following syntax:
void ffuunnccttiioonnNNaammee((ffoorrmmaall ppaarraammeetteerr lliisstt)) {{ ssttaatteemmeennttss }}
in which ssttaatteemmeennttss are usually declaration and/or executable statements. The formal
parameter list may be empty, in which case, in the function heading, the empty parentheses
are still needed.
FORMAL PARAMETER LIST
The formal parameter list has the following syntax:
ddaattaaTTyyppee&& vvaarriiaabbllee,, ddaattaaTTyyppee&& vvaarriiaabbllee,, ......
You must specify both the data type and the variable name in the formal parameter list.
The symbol && after ddaattaaTTyyppee has a special meaning; it is used only for certain formal
parameters and is discussed later in this chapter.
362 | Chapter 7: User-Defined Functions II
FUNCTION CALL
The function call has the following syntax:
functionName(aaccttuuaall ppaarraammeetteerr lliisstt);
ACTUAL PARAMETER LIST
The actual parameter list has the following syntax:
eexxpprreessssiioonn oorr vvaarriiaabbllee,, eexxpprreessssiioonn oorr vvaarriiaabbllee,, ......
in which eexxpprreessssiioonn can consist of a single constant value. As with value-returning
functions, in a function call, the number of actual parameters together with their data
types must match the formal parameters in the order given. Actual and formal para-
meters have a one-to-one correspondence. A function call results in the execution of
the body of the called function. (Functions with default parameters are discussed at the
end of this chapter.)
Example 7-1 shows a void function with parameters.
E X A M P L E 7 - 1
void ffuunneexxpp((int aa,, double bb,, char cc,, int xx)) {{ .. .. .. }}
The function ffuunneexxpp has four parameters.
Parameters provide a communication link between the calling function (such as mmaaiinn)
and the called function. They enable functions to manipulate different data each time
they are called. In general, there are two types of formal parameters: value parameters
and reference parameters.
Value parameter: A formal parameter that receives a copy of the content of the
corresponding actual parameter.
Reference parameter: A formal parameter that receives the location (memory address) of
the corresponding actual parameter.
When you attach && after the ddaattaaTTyyppee in the formal parameter list of a function, the
variable following that ddaattaaTTyyppee becomes a reference parameter.
7
Void Functions | 363
7
method pprriinnttSSttaarrss executes 30 times and prints 30 blanks. Also, because you want to
print a space between the stars, every iteration of the second for loop in the method
pprriinnttSSttaarrss prints the string "" **""—a blank followed by a star.
Next, consider the following statements:
int nnuummbbeerrOOffLLiinneess == 1 15 5;; int nnuummbbeerrOOffBBllaannkkss == 3 30 0;;
for ((ccoouunntteerr == 11;; ccoouunntteerr <<== nnuummbbeerrOOffLLiinneess;; ccoouunntteerr++++)) {{ pprriinnttSSttaarrss((nnuummbbeerrOOffBBllaannkkss,, ccoouunntteerr));; nnuummbbeerrOOffBBllaannkkss----;; }}
The for loop calls the function pprriinnttSSttaarrss. Every iteration of this for loop specifies the
number of blanks followed by the number of stars to print in a line, using the variables
nnuummbbeerrOOffBBllaannkkss and ccoouunntteerr. Every invocation of the function pprriinnttSSttaarrss receives
one fewer blank and one more star than the previous call. For example, the first iteration
of the for loop in the method mmaaiinn specifies 3300 blanks and 11 star (which are passed as
the parameters nnuummbbeerrOOffBBllaannkkss and ccoouunntteerr to the function pprriinnttSSttaarrss). The
for loop then decrements the number of blanks by 11 by executing the statement,
nnuummbbeerrOOffBBllaannkkss----;;. At the end of the for loop, the number of stars is incremented
by 11 for the next iteration. This is done by executing the update statement ccoouunntteerr++++
in the for statement, which increments the value of the variable ccoouunntteerr by 11. In
other words, the second call of the function pprriinnttSSttaarrss receives 2299 blanks and 22 stars
as parameters. Thus, the previous statements will print a triangle of stars consisting of
15 lines.
//Program: Print a triangle of stars
#include <>
using namespace ssttdd;;
void pprriinnttSSttaarrss((int bbllaannkkss,, int ssttaarrssIInnLLiinnee));;
int mmaaiinn(()) {{ int nnooOOffLLiinneess;; //variable to store the number of lines int ccoouunntteerr;; //for loop control variable int nnooOOffBBllaannkkss;; //variable to store the number of blanks
ccoouutt <<<< ""EEnntteerr tthhee nnuummbbeerr ooff ssttaarr lliinneess ((11 ttoo 2 20 0)) "" <<<< ""ttoo bbee pprriinntteedd:: "";; //Line 1
cciinn >>>> nnooOOffLLiinneess;; //Line 2
while ((nnooOOffLLiinneess << 00 |||| nnooOOffLLiinneess >> 2 20 0)) //Line 3 {{ ccoouutt <<<< ""NNuummbbeerr ooff ssttaarr lliinneess sshhoouulldd bbee "" <<<< ""bbeettwweeeenn 11 aanndd 2 20 0"" <<<< eennddll;; //Line 4
Void Functions | 365
ccoouutt <<<< ""EEnntteerr tthhee nnuummbbeerr ooff ssttaarr lliinneess "" <<<< ""((11 ttoo 2 20 0)) ttoo bbee pprriinntteedd:: "";; //Line 5 cciinn >>>> nnooOOffLLiinneess;; //Line 6 }}
ccoouutt <<<< eennddll <<<< eennddll;; //Line 7 nnooOOffBBllaannkkss == 3 30 0;; //Line 8
for ((ccoouunntteerr == 11;; ccoouunntteerr <<== nnooOOffLLiinneess;; ccoouunntteerr++++)) //Line 9 {{ pprriinnttSSttaarrss((nnooOOffBBllaannkkss,, ccoouunntteerr));; //Line 10 nnooOOffBBllaannkkss----;; //Line 11 }}
return 0 0;; //Line 12 }}
void pprriinnttSSttaarrss((int bbllaannkkss,, int ssttaarrssIInnLLiinnee)) {{ int ccoouunntt;;
for ((ccoouunntt == 11;; ccoouunntt <<== bbllaannkkss;; ccoouunntt++++)) //Line 13 ccoouutt <<<< '' '';; //Line 14 for ((ccoouunntt == 11;; ccoouunntt <<== ssttaarrssIInnLLiinnee;; ccoouunntt++++)) //Line 15 ccoouutt <<<< "" ** "";; //Line 16 ccoouutt <<<< eennddll;; }}
Sample Run: In this sample run, the user input is shaded.
Enter the number of star lines (1 to 20) to be printed: 1 155
In the function mmaaiinn, the user is first asked to specify how many lines of stars to print
(Line 1). (In this program, the user is restricted to 20 lines because a triangular grid of up
to 20 lines fits nicely on the screen.) Because the program is restricted to only 20 lines, the
while loop at Lines 3 through 6 ensures that the program prints only the triangular grid
of stars if the number of lines is between 1 and 20.
366 | Chapter 7: User-Defined Functions II
ccoouutt <<<< ""LLiinnee 77:: IInn tthhee ffuunnccttiioonn ffuunnccVVaalluueePPaarraamm,, "" <<<< ""aafftteerr cchhaannggiinngg,, nnuumm == "" <<<< nnuumm <<<< eennddll;; //Line 7 }}
Sample Run:
LLiinnee 22:: BBeeffoorree ccaalllliinngg tthhee ffuunnccttiioonn ffuunnccVVaalluueePPaarraamm,, nnuummbbeerr == 6 6 LLiinnee 55:: IInn tthhee ffuunnccttiioonn ffuunnccVVaalluueePPaarraamm,, bbeeffoorree cchhaannggiinngg,, nnuumm == 6 6 LLiinnee 77:: IInn tthhee ffuunnccttiioonn ffuunnccVVaalluueePPaarraamm,, aafftteerr cchhaannggiinngg,, nnuumm == 1 155 LLiinnee 44:: AAfftteerr ccaalllliinngg tthhee ffuunnccttiioonn ffuunnccVVaalluueePPaarraamm,, nnuummbbeerr == 6 6
This program works as follows. The execution begins at the function mmaaiinn. The
statement in Line 1 declares and initializes the int variable nnuummbbeerr. The statement in
Line 2 outputs the value of nnuummbbeerr before calling the function ffuunnccVVaalluueePPaarraamm; the
statement in Line 3 calls the function ffuunnccVVaalluueePPaarraamm. The value of the variable
nnuummbbeerr is then passed to the formal parameter nnuumm. Control now transfers to the
function ffuunnccVVaalluueePPaarraamm.
The statement in Line 5 outputs the value of nnuumm before changing its value. The
statement in Line 6 changes the value of nnuumm to 1155 ; the statement in Line 7 outputs
the value of nnuumm. After this statement executes, the function ffuunnccVVaalluueePPaarraamm exits and
control goes back to the function mmaaiinn.
The statement in Line 4 outputs the value of nnuummbbeerr after calling the function
ffuunnccVVaalluueePPaarraamm. The sample run shows that the value of nnuummbbeerr (Lines 2 and 4)
remains the same even though the value of its corresponding formal parameter nnuumm was
changed within the function ffuunnccVVaalluueePPaarraamm.
The output shows the sequence in which the statements execute.
After copying data, a value parameter has no connection with the actual parameter, so a
value parameter cannot pass any result back to the calling function. When the function
executes, any changes made to the formal parameters do not in any way affect the actual
parameters. The actual parameters have no knowledge of what is happening to the formal
parameters. Thus, value parameters cannot pass information outside the function. Value
parameters provide only a one-way link between actual parameters and formal para-
meters. Hence, functions with only value parameters have limitations.
Reference Variables as Parameters
The program in Example 7-4 illustrates how a value parameter works. On the other
hand, suppose that a formal parameter is a reference parameter. Because a reference
parameter receives the address (memory location) of the actual parameter, reference
parameters can pass one or more values from a function and can change the value of
the actual parameter.
368 | Chapter 7: User-Defined Functions II
7
Reference parameters are useful in three situations:
- When the value of the actual parameter needs to be changed
- When you want to return more than one value from a function
- When passing the address would save memory space and time relative to
copying a large amount of data
The first two situations are illustrated throughout this book. Chapters 9 and 12 discuss the
third situation, when arrays and classes are introduced.
Recall that when you attach && after the ddaattaaTTyyppee in the formal parameter list of a
function, the variable following that ddaattaaTTyyppee becomes a reference parameter.
You can declare a reference (formal) parameter as a constant by using the keyword const. Chapters 11 and 12 discuss constant reference parameters. Until then, the reference para- meters that you use will be nonconstant as defined in this chapter. From the definition of a reference parameter, it follows that a constant value or an expression cannot be passed to a nonconstant reference parameter. If a formal parameter is a nonconstant reference para- meter, during a function call, its corresponding actual parameter must be a variable.
E X A M P L E 7 - 5
Calculate Grade
The following program takes a course score (a value between 00 and 110000 ) and determines
a student’s course grade. This program has three functions: mmaaiinn, ggeettSSccoorree, and
pprriinnttGGrraaddee, as follows:
1. mmaaiinn
a. Get the course score.
b. Print the course grade.
2. ggeettSSccoorree
a. Prompt the user for the input.
b. Get the input.
c. Print the course score.
3. pprriinnttGGrraaddee
a. Calculate the course grade.
b. Print the course grade.
The complete program is as follows:
//This program reads a course score and prints the //associated course grade.
#include <> using namespace ssttdd;;
Reference Variables as Parameters | 369