User-defined functions


Introduction

As we mentioned earlier, one of the strengths of the C language is its function. These are very easy to define and use. We have used functions in every program we have discussed so far. However, these are basically limited to three functions, main (), printf (), and scanf ().

C functions can be classified into two categories, namely library functions, and user-defined functions. The main () is an example of a user-defined function. printf () and scanf () belong to the library function section. We have used other library functions like sqrt, cos, strcat, etc. The main difference between these two sections is that library functions do not need to be written by us where a user-defined function needs to be developed by the user when writing a program. However, a user-defined function becomes part of the C program library after the call. In fact, it is one of the strengths of the C language.


Need for user-defined functions

As pointed out earlier, main() is a specially recognized function in C. Each program must have a key function to indicate where to start the implementation of the program. Although it is possible to code any program using the main program, this leads to several problems. They may become too large and complex and as a result, the task of debugging, testing, and maintaining become difficult. If a program is divided into functional parts, each part may be independently coded and combined into a single unit. These independently coded programs are called subprograms that are must easier to understand, debug, and test. In C, such sub-programs are referred to as 'functions'.

There are times when certain operations or calculations are repeated at many points throughout a program. For example, we can use a number factorial at different points in the program. In such a situation, we can repeat the statements of the program where necessary. Another method is to design a function that can be called and used whenever needed. this saves both time and space.

This "division" approach obviously results in different advantages.

  1. It supports top-down modular programming as shown in the image below. In this programming style, the high-level argument of the overall problem is solved first while the functionality details of each lower level are described later.
  2. The length of the source program can be reduced by using the function in the appropriate place. This component is especially critical of microcomputers where memory space is limited.
  3. A faulty function is easy to detect and isolate for further investigation.
  4. A function can use many other programs. This means that no C programmer can build from scratch all over again based on what others have already done.
Top-down modular programming using functions