View All C Programs

 Previews Example  View All C Programs Next Example 

Program to swap using call by refernce in C

This program to swap using call by reference: C program to swap, explains easily difference between call by reference and call by value. In call by reference the addresses of actual arguments in the calling function are copied into formal arguments of the called function. This means that using these addresses we would have an access to the actual arguments and hence we would be able to manipulate them.
#include <stdio.h>
#include <conio.h>
  void swap( int *x, int *y )     // call by refrence
{
    int t ;
    t = *x ;
    *x = *y ;
    *y = t ;
    printf( "\nx = %d y = %d", *x,*y);
}

int main( )
{
    int a = 10, b = 20 ;
    swap ( &a, &b ) ;            // passing the address of values to be swapped
    printf ( "\na = %d b = %d", a, b ) ;
    getch();
}  
Result
x = 10     y = 20

a = 20     b = 10