Overview of Function

A function is a self-contained block of statements that perform a coherent task of some kind. Every C program can be thought of as a collection of these functions.

The programs written in C language are highil dependent on functions.

The C program is nothing but a combination of one or more functions.

Every C program starts with user defined function main( ). Each time when a new program is started, main( ) function must be defined. The main( ) calls another function to share the work.

Syntax

data type function (argument 1, argument 2)
   {
      //functions body;
   }

 

Example:-


#include <stdio.h>
int main()
{
    int x = 3;
    int x = 6;
    z = add`(x,y);    // Function Call 
    printf("z=%d",z);
}
    add(a,b);       // Function Definition
    {
      a+b;
    }

Output:

 z=9 

 

  • Any C program contains at least one function.
  • If a program contains only one function, it must be main( ).
  • If a C program execution always begins with main( ), so it will necessory to define at least one function.
  • There is no limit on the number of functions that might be present in a C program.
  • Each function in a program is called in the sequence specified by the function calls in main( ).
  • After each function has done its thing, control returns to main( ).When main( ) runs out of function calls, the program ends.
  • A function get call when the function name is followed by a semicolan( ; )
  • Any function can be called from any other function. Even main( ) can be called from other functions.
  • A function can be called any number of times.
  • A function can call itself. Such a process is called ‘recursion’.

Why use function ?

  • If we want to perform a task repetitively the it is not necessary to re-write the particular block of the program again and again. Shift the particular block of statements in a user-defined function. The defined can be used for any number of times to perform the task.
  • Using functions large programs can be reduced to smaller ones. It is easy to debug and find out the errors in it. It also increases readability.

Types of Function

There are basically two types of functions:

  • Library functions
  • User-defined functions

Library functions: These function are allready defined in header file.

Ex:- printf();, scanf();, sin();, cos();, etc..

User-defined functions: These function are defined by a user on his requirement.

Ex:- india();, msg(); etc..