User Defined Function
User Defined Function

Introduction User Defined Function (UDFS)

We have mentioned earlier that one of the strengths of C language is C functions. They are easy to define and use. We have user defined function in every program that we have discussed so far. However, they have been primarily limited to the three functions, namely, main, printf, and scanf. In this chapter, we shall consider in detail the following:

  • How a function is designed?
  • How a function is integrated into a program?
  • How two or more functions are put together?
  • How they communicate with one another?

C functions can be classified into two categories, namely, library functions and user-defined functions. main is an example of user-defined functions. printf and scanf belong to the category of library functions. We have also used other library functions such as sqrt, cos, strcat, etc. The main distinction between these two categories is that library functions are not required to be written by us whereas a user defined function has to be developed by the user at the time of writing a program. However, a user-defined function can later become a part of the C program library. In fact, this is one of the strengths of C language.

Need for User Defined Function

As pointed out earlier, main is a specially recognized function in C. Every program must have a main function to indicate where the program has to begin its execution. While it is possible to code any program utilizing only main function, it leads to a number of problems. The program may become too large and complex and as a result the task of debugging, testing, and maintaining becomes difficult. If a program is divided into functional parts, then each part may be independently coded and later combined easier to into a single unit. These independently coded programs are called subprograms that are much understand, debug, and test. In C, such subprograms are referred to as ‘functions’.

There are times when certain type of operations or calculations are repeated at many points throughout a program. For instance, we might use the factorial of a number at several points in the program. In such situations, we may repeat the program statements wherever they are needed. Another approach is to design a function that can be called and used whenever required. This saves both time and space.

This “division” approach clearly results in a number of advantages.

  1. It facilitates top-down modular programming as shown in image. In this programming style, the high level logic of the overall problem is solved first while the details of each lower-level function are addressed later.
  2. The length of a source program can be reduced by using functions at appropriate places. This factor is particularly critical with microcomputers where memory space is limited.
  3. It is easy to locate and isolate a faulty function for further investigations.
  4. A function may be used by many other programs. This means that a C programmer can build on what others have already done, instead of starting all over again from scratch.

A Multi Function Program

A function is a self-contained block of code that performs a particular task. Once a function has been designed and packed, it can be treated as a ‘black box’ that takes some data from the main program and returns a value. The inner details of operation are invisible to the rest of the program. All that the program knows about a function is: What goes in and what comes out. Every C program can be designed using a collection of these black boxes known as functions.

Consider a set of statements as shown below:

void printline(void)
{
    int i;
    for (i=1; i<40; i++)
             printf("-");
             printf("\n");
}

The above set of statements defines a function called printline, which could print a line of 39 character length.

void printline(void);/* declaration */
     main()
     {
          printline();
          printf("This illustrates the use of C functions\n");
          printline();
     }
       void printline(void)
     {
       int i;
       for(i=1; i<40; i++)
       printf("-");
       printf("\n");
      }

This program will print the following output: This illustrates the use of C functions

The above program contains two user-defined functions:

main() function
printline() function

As we know, the program execution always begins with the main function. During execution of the main, the first statement encountered is printline(); which indicates that the function printline is to be executed. At this point, the program control is transferred to the function printline. After executing the printline function, which outputs a line of 39 character length, the control is transferred back to the main. Now, the execution continues at the point where the function call was executed. After executing the printf statement, the control is again transferred to the printline function for printing the line once more.

The main function calls the user-defined printline function two times and the library function printf once. We may notice that the printline function itself calls the library function printf 39 times repeatedly.

Any function can call any other function. In fact, it can call itself. A ‘called function’ can also call another function. A function can be called more than once. In fact, this is one of the main features of using functions. Illustrates the flow of control in a multi-function program.

Except the starting point, there are no other predetermined relationships, rules of precedence, or hierarchies among the functions that make up a complete program.

The functions can be placed in any order. A called function can be placed either before or after the calling function. However, it is the usual practice to put all the called functions at the end. See the box “Modular Programming”.

User Defined Function
User Defined Function

Modular Programming

Modular programming is a strategy applied to the design and development of software systems. It is defined as organizing a large program into small, independent program segments called modules that are separately named and individually callable program units. These modules are carefully integranted to become a software system that satisfies the system requirements. It is basically a “divide and conquer” approach to problem solving.

Modules are identified and designed such that they can be organized into a top-down hierarchical structure (similar to an organization chart). In C, each module refers to a function that is responsible for a single task.

Some characteristics of modular programming are:

  1. Each module should do only one thing.
  2. Communication between modules is allowed only by a calling module.
  3. A module can be called by one and only one higher module.
  4. No communication can take place directly between modules that do not have calling-called relationship.
  5. All modules are designed as single-entry, single-exit systems using control structures.

Elements of User Defined Function

We have discussed and used a variety of data types and variables in our programs so far. However, declaration and use of these variables were primarily done inside the main function. As we mentioned in Chapter 4, functions are classified as one of the derived data types in C. We can therefore define functions and use them like any other variables in C programs. It is therefore not a surprise to note that there exist some similarities between functions and variables in C.

  • Both function names and variable names are considered identifiers and therefore they must adhere to the rules for identifiers.
  • Like variables, functions have types (such as int) associated with them.
  • Like variables, function names and their types must be declared and defined before they are used in a program.

In order to make use of a user-defined function, we need to establish three elements that are related to functions.

  1. Function definition.
  2. Function call.
  3. Function declaration.

The function definition is an independent program module that is specially written to implement the requirements of the function. In order to use this function we need to invoke it at a required place in the program. This is known as the function call. The program (or a function) that calls the function is referred to as the calling program or calling function. The calling program should declare any function (like declaration of a variable) that is to be used later in the program. This is known as the function declaration or function prototype.