Pages

Wednesday, December 2, 2009

Functions

In our day to day life we depend on several individuals to us in our daily activities. Like we depend on the plumber to fix the taps and pipes, carpenter to mend our furniture etc. we cannot perform all these tasks alone so we need the help and support of these persons. When we need their services we call them, they visit our place, perform the tasks and leave. Similarly in a program all the tasks cannot be performed by a single function or code. We’ll require many small programs to carry out the various tasks for us. These small programs are called functions.
By definition, function is “a small program that has a name and a particular task”. Of course, there are many predefined functions in C but since the requirements vary from user to user we cannot have a predefined function for every occasion. Therefore we need to create our own functions called “User Defined Functions”. A user defined function or UDF is a function created by the user as per his/her requirements.

Types of functions on the basis of declaration

On the basis of declaration we can divide functions in two categories

  1. Library functions : Those function which come precompiled in the language are called library functions or inbuilt functions. All such kind of functions is declared in some header files which must be included prior to calling these functions. For example the library function strcmp() is defined in the header file string.h, clrscr() in conio.h and isalpha() in ctype.h. The user is not required to create these functions as they are already declared in their respective header files.
    Examples : printf(),scanf(),strcmp(),strcpy(),clrscr(),getch() etc.
  2. User defined function: Functions which are declared by the user as per his/her need are called user defined functions. Since they are not pre-defined the user to provide all the definition to make it work. There can be no specific example of a user defined function since it depends on the user requirements.
Advantages of functions

1.
Functions encourage the concept of modular programming where a large problem is divided into small manageable chunks. These small parts are easy to understand and debug than a large problem.
2. One of the biggest advantages of a function is its reusability. A function once declared can be used again and again without having to retype the whole code.
3. Reusability in turn offers many other benefits like saving on resources. If a function can be called multiple times it saves both primary and secondary memory.
4. The time taken in compiling the code is also reduced since a function will be compiled just once irrespective of how many times it is being called.
5. Functions are tested for errors only once. Once the errors are removed we can call it as many times as we want.

0 comments:

Post a Comment