C Function

C Function


C functions are basic building blocks in a program. All C programs are
written using functions to improve re-usability, understandability and to
keep track on them. You can learn below concepts of C functions in this section in detail.

1. WHAT IS C FUNCTION?

A large C program is divided into basic building blocks called C function. C
function contains set of instructions enclosed by “{ }” which performs
specific operation in a C program. Actually, Collection of these functions

2. FUNCTION DECLARATION, FUNCTION CALL AND FUNCTION DEFINITION:

function definition
function call
function declaration

Example :

  #include lt;stdio.h gt;
 function prototype, also called function declaration
float square ( float x );                               
// main function, program starts from here
 
int main( )               
{
    float m, n ;
    printf ( "\nEnter some number for finding square \n");
    scanf ( "%f", &m ) ;
    // function call
    n = square ( m ) ;                      
    printf ( "\nSquare of the given number %f is %f",m,n );
}
 
float square ( float x )   // function definition
{
    float p ;
    p = x * x ;
    return ( p ) ;
}   

4. HOW TO CALL C FUNCTIONS IN A PROGRAM?

1.Call by value

2.Call by reference

1.Call by value

In call by value method, the value of the variable is passed to the
function as parameter.
The value of the actual parameter can not be modified by formal parameter
Different Memory is allocated for both actual and formal parameters.
Because, value of actual parameter is copied to formal parameter.

Example:

#include lt;stdio.h gt;
// function prototype, also called function declaration
void swap(int a, int b);          
 
int main()
{
    int m = 22, n = 44;
    // calling swap function by value
    printf(" values before swap  m = %d \nand n = %d", m, n);
    swap(m, n);                         
}
 
void swap(int a, int b)
{ 
    int tmp;
    tmp = a;
    a = b;
    b = tmp;
    printf(" \nvalues after swap m = %d\n and n = %d", a, b);
 
}


Call by reference :

In call by reference method, the address of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used by both parameters.

Example:

#include lt; stdio.h gt;
// function prototype, also called function declaration
void swap(int *a, int *b); 
 
int main()
{
    int m = 22, n = 44;
    //  calling swap function by reference
    printf("values before swap m = %d \n and n = %d",m,n);
    swap(&m, &n);         
}
 
void swap(int *a, int *b)
{
    int tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
    printf("\n values after swap a = %d \nand b = %d", *a, *b);
}



                  <<  PREVIEW >>



                  <<  NEXT    >>

Comments