as

Wednesday, 12 November 2014

Calling a Function in C


We can call function in C in 2 ways.
1.      Call by value
2.      Call by reference

Call by value

In this method, copies of the actual arguments are passed to the function. Actual arguments will not be modified by called function.

For Example:

#include<stdio.h>
// function prototype, also called function declaration
void swap(int p, int q);         

int main()
{
    int a = 10, b = 20;
    // calling swap function by value
    printf("Before swapping\n a = %d \n b=%d",a,b);
    swap(a,b);                        
}

void swap(int p, int q)
{
    int t;
    t = p;
    p = q;
    q = t;
    printf(" \nAfter swapping \n a = %d\n and b = %d \n", p, q);
}
Output: 

Call by reference (Using pointer)

In this method, addresses of the actual arguments are passed to the function using pointers. Actual arguments may be modified by called function. Memory is saved in this method.

For Example:

#include<stdio.h>
// function prototype, also called function declaration
void swap(int *p, int *q);

int main()
{

    int a = 17, b = 27;
    //  calling swap function by reference
    printf("Before swapping \n a = %d \n  b = %d",a,b);

//we have passed the addresses of a and b

    swap(&a, &b); 
    printf("\n After swapping \n a = %d \n b = %d", a, b);
      

}

void swap(int *p, int *q)
{
    int t;
    t = *p;
    *p = *q;
    *q = t;
}





Sponsored Links

Popular Posts

Comments

ShareThis

Google+ Followers

Google+ Badge