FUNCTION: ORGANIZING THE PROGRAM
As problems grow they become more difficult to solve. One problem solving strategy is to break a problem into smaller problems (sub-problems) then solve each of the sub-problems separately. This idea of breaking a big problem into smaller ones is reminiscent of the old expression divide and conquer. Similarly, a big program can be broken into subprograms that can be written and tested independently. Each of these subprograms is known as a function (unit) with a specific action (task) to perform. Normally, an application program (software) consists of thousands of lines of code (instructions). Without an organization (function), it is almost impossible to write, test, use, maintain, or reuse a large program. Can you imagine a team of programmers trying to write and manage a program without using functions?
There are two kinds of functions: built-in functions and user-defined functions. A built-in function is pre-constructed and is available for use in your program. A user-defined function must be built by the programmer.
C/C++ comes with a library of functions that are pre-programmed and ready for use in your program. You are already familiar with the C built-in functions
scanf(...), and printf (...), and the C++ function eof (...).
|
Important Built in Functions
|
|
|
Built-in Function |
Brief Description |
|
pow(n,m) |
A function that computes n to the power of m and is located in #include <cmath>. The library holds other mathematical functions such as sqrt( ) and sin( ).
|
|
strcmp( s1, s2 ) |
|
|
qsort(...) |
A function that sorts data using a highly recursive algorithm known as Quick Sort. The algorithm is discussed in Chapter 12, Sorting.
|
|
binsearch(...) |
A function that searches for a particular data element using the algorithm known as a Binary Search. A Binary Search continuously cuts an array of sorted data elements in half until the correct element is found. Binary search is covered in Chapter 11, Searching.
|
|
time(...) |
A function that returns the current date and time. Library: #include<ctime>
|
|
color(...) |
A function that sets a color for an object.
|
|
rand(...) |
A function that generates a random number. Library: #include <cstdlib>. |
![]()
HOW TO USE A BUILT-IN FUNCTION
It is very simple to use a built-in function; just place the function name in your program where you need to perform the task. Instead of writing your own function, call the built-in function to do the job. Remember to include the proper header file (directives) that contains the function definition.
The program of Figure 6.1a illustrates how to raise a number to a different power. For example, the built-in function pow( 3, 4 ) takes two values 3 and 4 and returns 81 as the result. Figure 6.1a shows the use of pow( ) using four different ways.

![]()
Not everything you want to accomplish is pre-programmed (a built-in function). There are times when you must write your own functions. In addition, you may want to know how the built-in functions are programmed. Suppose you want to write a program to find the square, cube or power of a number. How would you proceed? In order to make your own function, you have to name it and program it. You can then use the function name in your main program as if it was a built-in function. Figure 6.2a contains a program with the user defined functions mysquare( x ) and mycube( x ). These functions are used to differentiate and emphasize the user-defined functions versus built-in functions.
![]()

![]()

The function mycube( x ) can also be written with the use of the function mysquare( x ) , as illustrated in the following code fragment:

WHERE DO YOU PLACE A USER FUNCTION?
After you have written a function, where do you place it? There are four answers:
1) Place the function before the main program. The compiler favors this method because the function is known before its usage.
2) Place the function after the main program. Traditionally, this method is preferred because the program outline is shown first in the main program and the function details follow.
3) Place it in a separate file e.g. (squarefile.c or squarefile.cpp). The function's file can be compiled separately and then linked to the main program. A project can be built by adding the names of function files to the project. Each project may contain several function files.
4) Place it in a separate file by extension .h (squarefile.h) and include the file before the main, e.g #include "squarefile.h" , in a similar manner to the built in function #include <iostream.h>.
There are three identifying elements to a function:
1) Function Declaration - also known as a prototype.
2) Function Call - puts the function into use either by the main program or by other function(s).
3) Function Definition - where the body of function resides and the function action is performed.
In C, if the function definition is before the main program there is no need to declare (prototype) the function; however, in C++ prototyping is always needed. There are some compilers that skip the rule when the function is defined before the main.
HOW TO PROTOTYPE A FUNCTION
A function prototype is similar to the declaration of a variable. To prototype a function, you specify the kind of data the function will return (passes out) as well as the kind of data the function will communicate (passes in). There are instances when data is not passed into or out of a function.
You have been using the main program for quite a while but you probably did not realize that the main program is a function. If you look at the main program, it possesses the same form as a function. It has parentheses, braces, and a return value (return 0 is used most of the time). The main program is the main function that calls other functions. The main function can only be called by the operating system.
The overtime pay programs of Figures 6.3a and 6.3b provide the same result. Figure 6.3a does not use a function while Figure 6.3b does. Even though it looks like more work and overhead when using a function, it is beneficial to use a function rather than writing the code directly into the main program.






WHY FUNCTIONS ARE IMPORTANT
There are six specific reasons why functions are important:
1) Functions organize, modularize (by breaking programs into several units), and structure a program by outlining and defining the units separately.
2) Functions make programs easy to read, write, and debug.
3) Redundancy within the program is eliminated when using functions. A function is written once and called as many times as needed.
4) Functions allow for separate compilation. Each function can be written, compiled, and tested individually, and then linked at a later time.
5) Functions allow for reusability. A function can be reused by other programs and is easily maintained.
6) Functions facilitate teamwork. Specific functions can be assigned to individual programmers and then linked when necessary.
Whenever you write a program, divide the program into as many functions as possible, even if doing so causes more coding. The use of functions avoids problems. It is important to think of functions rather than writing the whole program as one large unit. Instead of writing the code within the main program, make a function call in main and code the function separately. For example, in the Payroll Program you can use a function to compute overtime pay and another function to find the tax rate. As programs become larger, more functions are added to the program. As you become more familiar with programming, the idea of the function becomes more interesting and useful.
FUNCTIONS AND THE PROGRAM
To use a function in a program you need to follow three steps:
1) Function Declaration ( also known as known as the function prototype ). You must indicate the return type and the number and type of parameters the function accepts. In the following example the function findmaximum takes three parameters of type integer and returns an integer.
![]()
![]()
or
2) Function Definition The function definition provides the actions the function performs. The function header and the body of the function are written here. In Figure 6.4, the function header is shown with the return type as well as the list of input parameters and their respective types. The opening and closing braces indicate the beginning and the end of the function. The return will send the maximum value of the integer input parameters named x, y, and z back to the calling function.


3) Function Call In order to use a function, the function must be called. To call a function, the name of the function and the correct parameters( if any) must be sent to the function definition. In the example of Figure 6.5a, the main program calls the function named findmaximum. The function finds the maximum of the three integer variables x, y, and z and displays the result. The complete program, including the code from Figure 6.4 is shown below. Figure 6.5b shows sample output of the program.



![]()
Each function performs a task on the data passed into the function known as a parameter or argument. It is important to provide the information a function needs to perform the task. One way to provide data to a function is to pass parameters (by listing name(s) and/or value(s)) in the parentheses of the function. In the example:
findmaximum( x, y, z ), the function findmaximum takes three parameters or arguments and finds the maximum of the three.
MATCHING THE PARAMETERS: ACTUAL WITH FORMAL
It is important for the parameters of the calling function to match the parameters of the function definition. When calling a function, the type of parameter and the order of its appearance must be the same as in the function definition. In Figure 6.5a, the function findmaximum passes three parameters, each as an integer value. In the calling function (main program), x, y and z are declared as integers. In the function header, the receiving values are placed in the variable x, y, and z respectively. The arguments or parameters in the calling function (main program) are known as actual arguments. The arguments in the called function are known as formal or dummy arguments. For simplicity, we have chosen the same name as the actual parameters. However, the formal parameter usually has a different name than the actual parameter. Variable names may be different. Notice that the formal variables x, y, and z are declared in the function findmaximum and this sets a separate memory location for x, y, and z.
FUNCTION WITH RETURN VALUE
A function is expected to perform a task and return a result. In the findmaximum function, the function is expected to return the maximum value to the calling function. Figure 6.5a once again illustrates the process.
Sometimes functions do not pass any parameters or return any value. Figure 6.6a illustrates such a program. The program has three functions named readdata, computedata, and printdata. Notice, these three function calls do not send any parameters and do not receive a value in return. You may be wondering if they are built-in system functions or user defined functions.


The two sections listed above and below the function main tell you that these are user- defined functions. These functions need to have source code written by the user that provides functionality when called.
In order to develop the code for these three functions, let us define the actions these functions provide.
|
Readdata |
asks the user to enter three numbers and then store these numbers in variables within the program.
|
|
Computedata |
takes the numbers entered by the user and add them together.
|
|
Printdata |
prints the numbers entered by the user and the result of the computedata calculation. |
Now that we understand what needs to be accomplished, we can start the process of writing the code to accomplish these tasks. The code for readdata is listed in figure 6.6b. Note the function asks the user to enter three numbers. This task is accomplished by using a cout statement asking the user for input. Then a cin statement is used to acquire and store the information provided by the user in the appropriate variables. Also note the use of the keyword void signifies no data is expected; therefore, no parameters are sent to the function and no data is returned from the function. When using the void keyword as a return type, the keyword return is not required at the end of the function definition.

The function named computedata takes all three numbers entered by the readdata function and adds them together. After the addition process, the sum is stored in a variable named sum. Figure 6.6c illustrates the function. Notice the use of the void keyword.


The last function of our program, named printdata, prints to the screen the numbers entered by the user as well as the sum of the inputted three numbers. The program is shown in figure 6.6d.


The next task is to piece the program together by integrating the main program with our user defined functions. How do we link the functions and the main program together?
There are two methodologies:
1) Place the main program first and place the functions after the main.
2) Place the functions first and then place the main program after the functions.
The second methodology is the preferred option. However, I prefer the first option, which allows a reader of a program to view the main first then discover the layout and objective of the program. When further explanation is needed, the reader may look to the functions below for a more detailed explanation. Either way, it all comes down to the style you prefer. The complete program is listed in Figure 6.6e and sample output is shown in Figure 6.6f.
After looking over Figure 6.6e, several questions may arise, such as:
When the program in Figure 6.6e is executed, the function main is called by the operating system. When execution has reached the main, each function is called and returned once the functions task is complete.
If the declaration of the variables is placed before the function main, then the main program and the entire collection of user defined functions may access these variables. This concept is called variable scoping.
A good exercise would be to move the variables declared above the function main into the function main and see the result. We will discuss global and local variables in more detail in the next few sections.



![]()



LOCAL AND EXTERNAL ( GLOBAL ) VARIABLES
Variables that are declared in the main program or in the functions of a program are said to be local. Variables declared outside of the main program or outside of the functions are said to be global or external. Local variables are variables that are defined locally. Global variables are defined externally.

![]()
![]()

In Figure 6.7a, variables x and y are declared in the main program; therefore, they are local to the main. As a result, myfunction cannot use these variables. However, the variable z is declared outside of the function myfunction and the main program. This allows the use of variable z by both the main program and myfunction.
At a glance, it appears easier to declare all variables outside the main program and all other function. Then every function can access the global variables as needed. So what is the drawback of using global variables? What happens if a function changes the value of a variable by mistake? Is it necessary to make an external variable visible to a function that has no interaction with that variable? A global variable holds its storage for the life of a program, even if it is not needed. Holding storage space for a variable that is not needed takes away resources needed to run a program. For simplicity, use external variables with caution.
EXTERNAL VARIABLE AND THEIR SIDE EFFECTS
If you have a headache, you take a pill. What happens if your headache goes away and you experience some hair loss? The loss of the hair is a side effect of taking the pill. Although this type of situation is rare, it can be costly. Figure 6.8a demonstrates the use of external variables and their unexpected side effect. Observe, the intended output of the program is 8 not 16. Since x is declared as an external variable, the return value of the function findsquare is 4, 4 is then multiplied by the value of x which has been set to 4 in the findsquare function.
![]()


![]()
SCOPE OF NAME
When a variable is declared either locally or externally, the variable has a life span and its own visibility. This determines where the variable exists, is used, and finally where it ceases to exist. When a variable is declared locally, the variables scope starts from the point of declaration and continues to the end of the block. Local variables no longer exist after the block where the variable was declared is exited. A local variable name overrides an external variable with the same name.
BLOCK AND VARIABLE DECLARATION
A block is represented by a pair of braces { }, one opens the block and the other closes it. When a variable name is declared within the braces, its scope begins at the point of declaration and ends at the closing brace.
To understand the concept of scope, look at the programs and output of Figures 6.9a and 6.10a. The output of both programs is the same.
![]()

![]()

![]()

![]()

DIFFERENCE BETWEEN C AND C++: BLOCK AND VARIABLE DECLARATION
In C, a variable is declared in the function main immediately following the beginning of the function block; while in C++, a variable can be declared anywhere after the block. The next two examples illustrate the difference in how C and C++ declare variables. Figure 6.11a shows the C version of a swap and Figure 6.11b shows the C++ version of the swap. The output for both programs is shown in Figure 6.11c.

![]()


![]()

The program of Figure 6.12a demonstrates functions using external variables. The program takes in three numbers, and then produces the sum of these numbers. Next, the average of the inputted numbers is calculated. Finally, all inputted numbers and their sum and average are printed.






Observe the program listed in Figure 6.12a. The functions within the function main outline the objectives of the program. The variables are defined above the functions and the main program.
The program listed in Figure 6.13a demonstrates functions using external variables, local variables and return values. The program takes in three numbers, produces the sum of the numbers, finds the average of the numbers, then prints out the numbers, their sum, and the average.






In the above program, the input numbers, the sum and the average are declared externally. Variables sum and average are also declared locally in findsum and findaverage. Each local variable has its own scope and storage, even though they possess the same name. The variables sum and average have the same value as sum and average in the function because the return value from each function assigns its corresponding value.
The program shown in Figure 6.14a demonstrates functions using external variables, local variables, and return values in conjunction with input parameters. The program takes in three numbers, sums the numbers, finds the average and prints out the numbers, their sum and the average.




![]()
In program 6.14a, the input variables are declared externally, while the variables sum and average are declared locally in the main program. The variable sum is also declared locally within the findsum function. The variable average is declared locally in the findaverage function. Each local variable has its own scope within the function where it is declared. Therefore, sum and average can be declared in many different functions and used locally, even though the variable name is used elsewhere. The variables sum and average of the function main have the same values as sum and average in the functions findsum and findavg because these functions return their local variable value to the main functions corresponding local variable.
In C/C++, when a parameter is passed to a function, by default only the value of the parameter is sent to the function. In other words, a copy of the variable value is made and sent to the function. The called function does not communicate back to the calling function. That is the called function takes but does not give back any changes to the calling functions parameters.
A large program is divided into many functions and functions can be placed in many files. A function can unintentionally change the value of a variable and this may be undesirable and as a consequence cause problems. To avoid an unintentional change to an original value, C/C++ encourages pass by value. Any other passing mechanism requires additional knowledge and steps. Figure 6.15a illustrates passing by value to functions. Notice that the program initializes the variable x equal to 5 in the function main. Before the nochange function call the value of x is equal to 5. In the function nochange, the copy of the value of x is incremented to 6 and displayed. And when the function nochange returns control to the function main, the value of x is displayed again, and the value of x returns to 5.
This simple program completely illustrates the default mechanism for sending parameters to a function. As a result, many errors are eliminated when passing parameters to functions.

![]()

PASSING A PARAMETER VALUE BACK - TWO WAY COMMUNICATION
There are times when we need to send a parameter to a function and have the changes take effect. In other words, any change to the variable passed (formal parameter) will alter the original variable. There are two ways that a parameter value can change when sent to a function:
1.) C Method (traditional method): In order for the value of a parameter to change when passed to a function, certain steps must be followed. In this method, the address of the parameter is sent to the function where it is stored as a pointer variable. In the function, the value of the pointer is accessed by indirection. The indirection operator is the multiplication sign ( * ). Since the formal variable has the same address as the actual variable, any change to the formal value is reflected on the actual variable. The content of the pointer variable impacts the actual parameter, which is why this method is called pass by pointer. This passing of a memory address is the difference between passing by value and passing by pointer. Presently, the concept may be a little confusing. At a later time, we will review passing parameters by pointer when we discuss pointer variables.
2.) C++ Method (new method): Pass By Reference. Passing a parameter by reference (pass by reference) simplifies the C method of passing by pointer. The user does not need to know about pointer variables and the indirection operator to access the content of a variable. With pass by reference, the receiving function takes the address of the parameter and any change to the variable is reflected on the passing variable. No additional typing is needed except in the function heading where an ampersand (&) is placed before the variable.
There are three steps to follow in order to pass a parameter by pointer:
1.) From the calling function, send the address of the parameter to be passed.
2.) In the function declaration, declare the receiving parameter as a pointer variable.
3.) De-reference the pointer variable by using the indirection operator ( * ). The asterisk denotes the value the pointer variable is pointing to.
Figure 6.16a illustrates how the address of a variable is passed and how any change to the memory address results in the change of the original variable value.


![]()
C++ simplifies the C method by declaring the receiving variable as a reference. To declare a variable as a reference, precede the variable with an ampersand (&) in the function heading and C++ automatically de-references it. Figure 6.17a illustrates passing a parameter to a function by reference.

![]()


When reading a value in C using scanf, you may wonder why you have to use the address of operator ( & ). Look at the following line of code:
![]()
![]()
The task of scanf is to bring a value back, for example, from the keyboard. This is the reason it is necessary to send the address the value will be stored in. With printf it is not necessary to use the address of the operator because the task of printf is simply to take a value and display it.
THE NAME OF AN ARRAY AS AN ADDRESS
Interestingly in C/C++, the name of an array is an address; therefore, it is not necessary to precede the array name with an ampersand ( & ). When the name of an array is sent to a function, the actual variable is automatically sent. Any changes made will affect the original array. Figure 6.18a illustrates the syntax needed to send an array to a function.