Chapter 9 - User-Defined Functions in C++ Language

A function is a group of statements which together perform a task. Every C++ program has at least one function, which is the main() function. There are two types of functions in C++ which are 1) pre-defined functions which some of them has been discussed in the previous chapters of this book, and the other type is called 2) user-defined function. This chapter presents the fundamentals of defining and using a user-defined function.

 

User-defined function

 

C++ allows programmer to define functions according to their need. These functions are known as user-defined functions. To create a user-defined function, it involves function declaration known as the function prototype and function definition which defines the statements that the user-defined function will perform.

The following discussions is an example of creating a user-defined function that returns the area of a rectangle. The data needed to compute the area of a rectangle is the length and width. The name of the function would be getArea().

 

User-defined function prototype

A function prototype is simply the declaration of a function that specifies the function's name, parameters and return type. It doesn't contain function body. A function prototype gives information to the compiler that the function may later be used in the program.

 

Syntax of user-defined function prototype:

<ret-type> <func-name>(<type par1>, <type parN>,..);

 

In the syntax, the <ret-type> is the return data type of the user-defined function. The return type in the example is the area of a rectangle hence, it could be an integer data type. The <func-name> is the function name of the user-defined function, and enclose with the ( ) parentheses are the user-defined function's parameters. The parameters are the type(s) of data, which may be passed to the function, hence in the example, the needed data are the length and width of the rectangle which could be an integer data type. A user-defined function may have 0 or N number of parameters. If no parameter is needed, just leave the ( ) parentheses empty.

 

Below is the creation of the function prototype of the user-defined function getArea():

int getArea(int len, int wid);

 

The return type is integer which represents the area of the rectangle, and the parameters needed are the length and width with the names len and wid respectively of type integers.

Figure 9.1 presents the place where the function prototype should be declared.

 

Figure 9.1

 

Line 4 presents the declaration of the function prototype, and it must be declared before the main() function.

 

User-defined function definition

A function definition of a user-defined function contains the block of statement that the function will perform.

 

Syntax of user-defined function definition:

<ret-type> <func-name>(<type par1>, <type parN>,..)

{

<statement(s)>;

}

 

The first line in the syntax is similar to the function prototype but note that it should not end with a ; semi-colon. The <statement(s) is the body of the user-defined function which can be a single statement or block of statements. When a user-defined function is called, the execution of the program is transferred to the function definition. The compiler starts executing the codes inside the body of a function, hence if the user-defined function is not called, its body of statement(s) will not be executed.

 

Below is the creation of the function definition of the user-defined function getArea():

int getArea(int len, int wid)

{

int iArea;

iArea=len*wid;

return iArea;

}

 

The function definition contains the statement(s) that the function will perform. In this example, the area of the rectangle is computed by getting the product of length and width of the rectangle, and the return keyword is used to return the value to the calling statement.

Figure 9.2 presents where the function definition should be placed.

 

Figure 9.2

 

Lines 12 to 17 presents the function definition of the getArea() user-defined function. The statement(s) in the function definition in lines 14 to 16 will only be executed when it is called.

 

Calling a user-defined function

Execution of the program is transferred to the user-defined function definition by calling it. To call a user-defined function, just use its name and include the arguments if there are, which should be passed to it.

 

Syntax of calling a user-defined function:

<func-name> (<arg1>, <argN>,..)

 

In the syntax, <arg1> to <argN> are the actual value that should be passed to the user-defined function which should conform to the data type declared in the user-defined function's parameters. The difference between parameters and arguments is that parameters are declaration of the data type and the variable names (the term is usually used in the function prototype), and on the other hand, arguments are the actual value that these variables with hold (the term is usually used in calling of function) .

Figure 9.3 presents a working program that computes the area of a rectangle using a user-defined function

 

Figure 9.3 (source file name: ch9sample1.cpp)

 

Line 3 presents the user-defined function prototype. The int len, int wid inside the ( ) parentheses are called parameters, hence this function has two parameters of type integer.

Line 6 presents declaration of local variables inside the main() function named intLen and intWid of type integer.

Lines 8 to 12 asks the user to enter values for the length and width of the rectangle and each of which is assigned to variables intLen for length and intWid for the width.

Line 14 prints "The area of rectangle is" and the function calling is executed which returns a integer value of whatever is returned in the getArea(int Len, intWid) function definition. The getArea(intLen, intWid)in line 14 is the way how to call a function definition and intLen and intWid are the arguments that will be passed to the function-definition in line 21, and in this example, upon executing line 14, execution of the program goes to line 21.

In line 21, the parameters of the getArea() which are int len and int wid, has now a value based from the arguments passed on it in the calling statement in line 14.

Lines 23 to 25 are the statements that the function will perform, and in this example, it computes the area of rectangle by multiplying the variable len by wid which represents the length and width of the rectangle.

In line 25, the return keyword is required for user-defined function that has a return value, hence, the return value in this example is the value of variable iArea which will be returned back to line 14 printing the area of the rectangle.

Figure 9.4 presents the possible output of the program.

 

Figure 9.4

 

Code listings of figure 9.3

#include<iostream>

using namespace std;

int getArea(int len, int wid);

int main()

{

int intLen, intWid;

 

cout<<"Enter the length of the rectangle: ";

cin>>intLen;

cout<<"Enter the width of the rectangle: ";

cin>>intWid;

cout<<"The area of rectangle is "<<getArea(intLen, intWid);

 

fflush(stdin);

getchar();

return 0;

}

 

int getArea(int len, int wid)

{

int iArea;

iArea=len*wid;

return iArea;

}

 

Things to consider in functions:

 

1. A C++ program can have 0 or more user-defined functions as long as each user-defined function has a function prototype, function definition, and function calling to execute its intended purpose.

 

2. Some functions perform the desired operations without returning a value. If this is the case, the return type should be the keyword void. Figure 9.5 presents a sample program that performs printing statements without a return value and does not pass any parameter.

 

Figure 9.5 (source file name: ch9sample2.cpp)

 

Line 5 presents the function prototype of the user-defined function which uses the keyword void as its return type because the function will not return any value. Line 10 presents the calling of the function, and when the function is called, the execution of the program is transferred to the function definition in line 18. After executing the function definition's statements in lines 20 to 24, the execution of the program is transferred back to the next line that follows the calling statement which is line 11 onwards. Figure 9.6 presents the output of the program.

 

Figure 9.6

 

Code listings of figure 9.5

#include<iostream>

using namespace std;

 

//Function prototype

void printWelcome();

 

int main()

{

//Calling of the function printWelcome()

printWelcome();

 

fflush(stdin);

getchar();

return 0;

}

 

/*Function definition*/

void printWelcome()

{

cout<<"Hello Reader!"<<endl;

cout<<"Welcome to the 3riple S Way"<<endl;

cout<<"of Learning C++ Language."<<endl;

cout<<"We Thank you for entrusting"<<endl;

cout<<"your learning with us.";

}

 

3. The main() function is the only function required in all C++ programs. The main() function can also return a value as needed, but most of the program does not do this, hence the return 0 is usually use.

 

4. In using user-defined functions, the scope of variables should be considered. As discussed in chapter 3 there are several areas where the variable is declared which defines their scope. Figure 9.7 presents the illustration of the scope of variables.

 

Figure 9.7 (source file name: ch9sample3.c)

 

Line 5 int iArea; is a globally declared variable, which means that this variable can be used in all functions in the program. Global variables are declared before the main() function, hence all functions can used global variable(s). Notice the iArea variable is used inside the main() function in line 16 and also used inside the getArea() function in line 23.

Line 9 int intLen, intWid; are locally declared variables. Local variables are declared inside a function and this variable can only be used in the function where it is declared. intLen and intWid cannot be used in the getArea() function.

In line 25's int getArea(int len, int wid), len and wid are called parameter variables as they are declared as a formal parameter of a user-defined function. Parameter variables are similar to local variables wherein they can only be used in the function where they are declared.

Figure 9.8 presents the possible output of the program.

 

Figure 9.8

 

Code listings of figure 9.7

#include<iostream>

using namespace std;

 

int getArea(int len, int wid);

int iArea;

 

int main()

{

int intLen,intWid;

cout<<"Enter the length of the rectangle: ";

cin>>intLen;

cout<<"Enter the width of the rectangle: ";

cin>>intWid;

iArea=getArea(intLen, intWid);

cout<<"The area of rectangle is "<<iArea;

 

fflush(stdin);

getchar();

return 0;

}

 

int getArea(int len, int wid)

{

iArea=len*wid;

return iArea;

}

 

Self-assessment questions

 

Indicate whether the statement is true or false.

 

1. User-defined functions are best used for reusable code, or code that you know works and do want make use of it throughout development.

 

2. If you find yourself tempted to use copy and paste on a particular block of code, even once, then you should move the code into a array.

 

3. A user-defined function can either return a value after performing a task or just perform a task without returning a value.

 

4. User-defined functions are declared similar to array variables.

 

5. A function name must be unique (not assigned to any other function or variable).

 

Answer the following.

 

6. Write a user-defined function prototype named "valfunc" that has one parameter named x of data type integer and this function does not return any value.

 

7. Write a user-defined function prototype named "numfunc" without parameter and this function does not return any value.

 

8. Write a user-defined function prototype named "charfunc" that has three parameters named x,y, z. The two variables are integer type and onefloat data type respectively, and returns a char type value.

 

9. Write a statement the calls a user-defined function named "xfunc" and passes two constant values of 5 and 10 as its arguments.

 

10. What return type keyword should be used, if the user-defined function will not return a value.