Lesson -8 User Defined Function

8.1 INTRODUCTION

One of the main strength of C language is the use of functions. They are easy to define and use. We have used functions in every program that we have discussed so far. However, they have been primarily limited to three functions, namely main, printf and scanf. C functions can be classified into two categories:

  • User defined functions

  • Library functions

main is an example of user defined functions. printf and scanf belongs to the category library functions. The main difference between these two types functions is that library functions are not required to be written by us whereas user defined functions has to be developed and written by the user.

8.2 DEFINITION OF FUNCTION

Function is a self-contained program segment that carries out some specific well-defined task. Every C program consists of one or more functions. The most important function is main(). Program execution will always begin by carrying out the instruction in main. The definitions of functions may appear in any order in a program file because they are independent of one another. A function can be executed from anywhere within a program. Once the function has been executed, control will be returned to the point from which the function was accessed. Functions contain special identifiers called parameters or arguments through which information is passed to the function and from functions information is returned via the return statement. It is not necessary that every function must return information, there are some functions also which do not return any information for example the system defined function printf.

Before using any function it must be defined in the program. Function definition has three principal components:

  • First line

  • Parameter declarations

  • Body of the functions

The first line of a function definition contains the data type of the information return by the function, followed by function name, and a set of arguments or parameters, separated by commas and enclosed in parentheses. The set of arguments may be skipped over. The data type can be omitted if the function returns an integer or a character. An empty pair of parentheses must follow the function name if the function definition does not include any argument or parameters.

The general term of first line of functions can be written as:

data-type function-name (formal argument 1, formal argument 2…formal argument n)

The formal arguments allow information to be transferred from the calling portion of the program to the function. They are also known as parameters or formal parameters. These formal arguments are called actual parameters when they are used in function reference. The names of actual parameters and formal parameters may be either same or different but their data type should be same. All formal arguments must be declared after the definition of function. The remaining portion of the function definition is a compound statement that defines the action to be taken by the function. This compound statement is sometimes referred to as the body of the function. This compound statement can contain expression statements, other compound statements, control statements etc. Information is returned from the function to the calling portion of the program via the return statement. The return statement also causes control to be returned to the point from which the function was accessed. In general terms, the return statement is written as:

return expression;

The value of the expression is returned to the calling portion of the program. The return statement can be written without the expression. Without the expression, return statement simply causes control to revert back to the calling portion of the program without any information transfer. The point to be noted here is that only one expression can be included in the return statement. Thus, a function can return only one value to the calling portion of the program via return. But a function definition can include multiple return statements, each containing a different expression. Functions that include multiple branches often require multiple returns. It is not necessary to include a return statement altogether in a program. If a function reaches the end of the block without encountering a return statement, control simply reverts back to the calling portion of the program without returning any information.Let us consider an example of function without returning any information.

            #include <stdio.h>

            void maxi(int, int); /*function declaration*/

            main()

            {

                        int x,y;

                        printf(“Enter two integer values”);

                        scanf(“%d %d”’ &x,&y);

                        maxi(x,y); /*call to function*/

            }

            void maxi(int x, int y) /*function definition*/

            {

                        int z;

                        z=(x>=y)?x:y;

                        print(“\n\n Maximum value %d”,z);

            }

This ‘maxi’ function do not return any value to the calling program, it simply returns the control to the calling programs, even if return statement is not present, then also program will work efficiently.

8.3 ACCESSEMENT OF A FUNCTION

A function can be accessed by specifying its name, followed by a list of parameters or arguments enclosed in parentheses and separated by commas. If the function call does not require any arguments an empty pair of parentheses must follow the function’s name. The function call may appear by itself or it may be one of the operands within a more complex expression. The parameters in the body of the functions are called actual arguments as stated earlier; they may be expressed as constants, single variables or more complex expressions. Let us consider another example of function.

            #include <stdio.h>

            int sum_v(int,int);

            void main()

            {

                        int a,b,c;

                        printf(“Enter two numbers”);

                        scanf(“%d%d”, &a,&b);

                        c=sum_v(a,b,);

                        printf(“\n The sum of two variables is %d\n,”,c);

            }

            int sum_v(int a, int b)

            {

                        int d;

                        d=a+b;

                        return d;

            }

This program returns the sum of two variables a and b to the calling program from where sum_v is executing. The sum is present in the variable c through the ‘return d’ statement. There may be several different calls to the same function from various places within a program. The actual parameters may differ from one function call to another. Within each function call, the actual arguments must correspond to the formal arguments in the function definition, i.e. the number of actual arguments must be same as the number of formal arguments and each actual argument must be of the same data type as its corresponding formal argument. Let us consider an example.

            #include <stdio.h>

            maxi(int, int);

            void main()

            {

                        int a,b,c,d;

                        printf(“\n Enter value of a=”);

                        scanf(“%d”, &a);

                        printf(“\n Enter value of b=”);

                        scanf(“%d”,&b);

                        printf(“\n Enter value of c=”);

                        scanf(“%d”, &c);

                        d=maxi(a,b);

                        printf(“\n maximum =%d”, maxi(c,d));

            }

            maxi(int x,int y);

            {

                        int z;

                        z=(x>=y)? x:y;

                        return z;

            }

The function maxi is accessed from two different places in main. In the first call actual rguments are a, b and in the second call c, d are the actual arguments.

If a function returns a non-integer quantity and the portion of the program containing the function call precedes the function definition, then there must be a function declaration in the calling portion of the program. The function declaration effectively informs the compiler that a function will be accessed before it is defined. A function declaration can be written as.

datatype function_ name ( );

Function calls can span several levels within a program; function A can call function B so on.

8.4 PASSING ARGUMENT TO A FUNCTION

Arguments can be passed to a function by two methods, they are called passing by value and passing by reference. When a single value is passed to a function via an actual argument, the value of the actual argument is copied into the function. Therefore, the value of the corresponding formal argument can be altered within the function, but the value of the actual argument within the calling routine will not change. This procedure for passing the value of an argument to a function is known as passing by value. Let us consider an example

            #include <stdio.h>

            void main()

            {

                        int x=3;

                        printf(“\n x=%d(from main, before calling the function”),x);

                        change(x);

                        printf(“\n\nx=%d(from main, after calling the function)”,x);

            }

            change(int x)

            {

                        x=x+3;

                        printf(“\nx=%d(from the function, after being modified)”,x);

            }

The original value of x (i.e. x=3) is displayed when main begins execution. This value is then passed to the function change, where it is sum up by 3 and the new value displayed. This new value is the altered value of the formal argument that is displayed within the function. Finally, the value of x within main is again displayed, after control is transferred back to main from change.

x=3 (from main, before calling the function)

x=6 (from the function, after being modified)

x=3 (from main, after calling the function)

Passing an argument by value allows a single-valued actual argument to be written as an expression rather than being restricted to a single variable. But it prevents information from being transferred back to the calling portion of the program via arguments. Thus, passing by value is restricted to a one-way transfer of information. Arrays are passed differently than single-valued entities. If an array name is specified as an actual argument, the individual array elements are not copied to the function. Instead the location of the array is passed to the function. If an element of the array is accessed within the function, the access will refer to the location of that array element relative to the location of the first element. Thus, any alteration to an array element within the function will carry over to the calling routine.

8.5 SPECIFICATION OF DATA TYPES OF ARGUMENTS

The calling portion of a program must contain a function declaration if a function returns a non-integer value and the function call precedes the function definition. Function declaration may be included in the calling portion of a program even if it is not necessary. It is possible to include the data types of the arguments within the function declaration. The compiler will then convert the value of each actual argument to the declared data type and then compare each actual data type with its corresponding formal argument. Compilation error will result if the data types do not agree. We had already been use, data types of the arguments within the function declaration. When the argument data types are specified in a function declaration, the general form of the function declaration can be written as:

data-type function name (argument type1, argument type2, … argumenttype n);

Where data-type is the data type of the quantity returned by the function, function name is the name of function, and argument type/refer to the data types of the first argument and so on. Argument data types can be omitted, even if situations require a function declaration. Most C compilers support the use of the keyword void in function definitions, as a return data type indicating that the function does not return anything. Function declarations may also include void for the same purpose. In addition, void may appear in an argument list, in both function definitions and function declarations, to indicate that a function does not require arguments.

8.6 FUNCTION PROTOTYPES AND RECURSION

Many C compilers permits each of the argument data types within a function declaration to be followed by an argument name, that is:

data-type function name (type1 argument 1, type 2 argument2…type n argument n);

Function declarations written in this form are called function prototypes. Function prototypes are desirable, however, because they further facilitate error checking between the calls to a function and the corresponding function definition. Some of the function prototypes are given below:

int example (int, int); or int example (int a, int b);

void example 1(void); or void example 1(void);

void fun (char, long); or void fun (char c, long f );

The names of the arguments within the function declaration need not be declared elsewhere in the program, since these are “dummy” argument names recognized only within the declaration. “C” language also permits the useful feature of ‘Recursion’.

Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. The process is used for repetitive computations in which each action is stated in terms of a precious result. In order to solve a problem recursively, two conditions must be satisfied. The problem must be written in a recursive form, and the problem statement must include a stopping condition. The best example of recursion is calculation of factorial of a integer quantity, in which the same procedure is repeating itself. Let us consider the example of factorial:

#include <stdio.h>

long int rec(int number);

void main()

{

int no, fact ;

printf ( "\nEnter any number " ) ;

scanf ( "%d", &no ) ;

fact = rec ( no ) ;

printf ( "Factorial value = %d", fact ) ;

}

rec ( int x )

{

int f ;

if ( x == 1 )

 return ( 1 ) ;

else

f = x * rec ( x - 1 ) ;

return ( f ) ;

}

And here is the output for four runs of the program

Enter any number 1

Factorial value = 1

Enter any number 2

Factorial value = 2

Enter any number 3

Factorial value = 6

Enter any number 5

Factorial value = 120

The point to be noted here is that the function ‘rec’ calls itself recursively, with an actual argument (n-1) that decrease in value for each successive call. The recursive calls terminate the value of the actual argument becomes equal to 1. When a recursive program is executed, the recursive function calls are not executed immediately. Instead of it, they are placed on a stack until the condition that terminates the recursion is encountered. The function calls are then executed in reverse order, as they are popped off the stack. The use of recursion is not necessarily the best way to approach a problem, even though the problem definition may be recursive in nature.

Last modified: Monday, 28 October 2013, 9:58 AM