Functions in C


Why functions ?


  • Reduce length of source program by avoiding use of repetitive code.
  • If there is an error in a program,then rather than searching the whole program of say 10,000 lines its always better to search error in a particular function based on particular functionality.So,functions provide way for easy error searching.
  • Makes program more readable.
  • Frequently used functions can be put into a header file and we can reuse this header file by including it in other programs.
  • Individual functions can be easily tested and built(unit testing).



Concept


Function is a group of statements that performs a specific task.

  • Function declaration:
return_type function_name(parameter_list);


return_type : What is function going to return to the called function? (eg. void,int,pointer,etc)

function_name: Name of the function is generally given according to the task it is going to perform.

eg. If a function is calculating average then a suitable name like calc_Avg should be given.

parameter_list: It is like a placeholder.It specifies variables of which data types would be passed during function call.Parameter names are not required,only their datatypes are required.Note:Specifying both would also work.A function containing no parameters would have empty brackets.

float calc_Avg(int);
specifies that function calc_Avg would take an integer as parameter return an integer.

  • Function call:

function_name(arguments to be passed);
Arguments to be passed are also called as actual arguments.You only need to pass the parameter names and not their datatypes.

  • Function definition:
return_type function_name(parameter_list)
{
    ...
    function body
    ...
}

parameter_list:  Arguments passed from function call are collected in this list.Parameter names with their datatypes is required.Parameters  in this list are also called as formal parameters.
  eg.
calc_Avg(sum);               //function call

float calc_Avg(int s)        //function definition
{
    ...
    ...
    return avg;
}


Function body: collection of statements that define what a function does.

Other terms have been covered in function declaration.

  •  A simple program to calculate factorial of a number using functions
#include <stdio.h>                             //includes file stdio.h 

int factorial(int);                            /* function declaration of function factorial that
                                                  takes an integer and returns an integer */                              
int main()
{
    //declaration of local variables
    int no,fact;

    scanf("%d",&no);                                //function defined in stdio.h  

    printf("Enter number ");                       //function defined in stdio.h 

    fact=factorial(no);                           //function call

    printf("Factorial of number is %d",fact);

    return 0;
}

//function definition

int factorial (int num)                          //returns an integer to main() i.e calling function
{
    int i,fact=1;                               //function body
    for(i=num;i>=1;i--)
        fact=fact*i;
    return fact;
}

  • Mechanisms for passing arguments to a function

1.  Pass by value
Lets look at an example to accept radius and calculate area of circle in an function.
#include <stdio.h>

void acc_calc(float,float);

int main(void) 
{
    float rad,area;
    acc_calc(rad,area);
    return 0;
}

void acc_calc(float pvrad,float pvarea)
{
    printf("Enter radius ");
    scanf("%f",&pvrad);
    pvarea = 3.14 * (pvrad) * (pvrad);
    printf("\nRadius = %.2f\nArea = %.2f",pvrad,pvarea);
}
We have passed rad and area by value then values of both are copied in different memory locations and changes are made on this local copies.Now,picture is as shown below

             rad          area        pvrad         pvarea
Address   0xbfbda7a8   0xbfbda7ac   0xbfbda790    0xbfbda794
So ,by changing pvrad and pvarea , we are not changing contents at memory location of main() ‘ s rad and area . So suppose we had to print the radius and area in main(),we would have not been able to do this using this technique as
1.Changes are not reflected in main as we operate on local copies.
2.Return statement can return only one value.

2.  Pass by address
Lets look at an example to accept radius and calculate area of circle in an function and you have to print both radius and calculated area in main().Now return would not work here because we can’t return more than 1 value from function.
So we use Pass by address mechanism
#include <stdio.h>

void acc_calc(float*,float*);

int main(void) 
{
    float rad,area;
    acc_calc(&rad,&area);
    printf("\nRadius = %.2f\nArea = %.2f",rad,area);
    return 0;
}

void acc_calc(float* prad,float* parea)
{
    printf("Enter radius ");
    scanf("%f",prad);
    *parea = 3.14 * (*prad) * (*prad); 
}
If we would have passed rad and area by value then values of both are copied in different memory locations and changes are made on this local copies.So changes are not reflected in main.But if you pass by address,then the picture is as shown below
rad area prad parea
Address 0xbf9f2cf8 0xbf9f2cfc
Value 0xbf9f2cf8 0xbf9f2cfc

So ,by changing *prad and *parea , we are directly changing contents at memory location of main() ‘ s rad and area .So, we are not required to return anything as changes are directly reflected in main().


More


Recursion

1 comment: