facebook like button

01 June, 2011

program 51: user defined swap function in C

The need: 
      This is a program to demonstrate the use of pointers in C program. This shows how a pointer solve problem in swapping with user defined function. The swap function implemented here can be used in many bigger programs to swap the values of 2 variables.

The code: 
--------------------------------------------
#include<stdio.h>
void swap(int *a, int *b);
main()
{
  int x=4,y=5;
  printf("values before swap are\n");
  printf("x=%d\ty=%d\n",x,y);
  swap(&x,&y);
  printf("values before swap are\n");
  printf("x=%d\ty=%d\n",x,y);
  return 0;
}
void swap(int *a, int *b)
{
 int tmp;
 tmp=*a;
 *a=*b;
 *b=tmp;
}
--------------------------------------------

The approach: 
First of all copy, paste, compile and run the program. This is a simple program just to show how pointers can be used to pass variables by reference in a program. The term "pass by reference" means addresses of variables are passed as arguments to function. Open post55 of this blog and look at the program given there. This program is a cure for the problem encountered there and gives the desired output. How this is done is explained in next para.
    Till now all of us knew that when a function was called it took only values of arguments passed to it. Now here we passed addresses (which are also some values). These values are assigned to other temporary variables in user defined functions. Now look at point 6 of points to remember about pointers section in post55 of this blog. So this temporary variable now points to the variable whose address is passed and can be use to do any operation on it by directly going to that location in memory.The situation is just like the one described in the analogy given below (RP's picture analogy).
    Suppose I have a picture named A located somewhere. I give you a carbon copy of this picture. You have carbon copy now so you know how original picture looks but don't know where the original picture is located. Now I say draw something more on picture. Will you be able to make any changes in original picture A??? The answer is NO. Its obvious that whatever changes you will make will be made only on the carbon copy of that picture which you have. Same is the case when the carbon copy of values is passed to a function. Suppose I also have a paper on which the location of original picture is written so that you can go to the original picture A. I give you carbon copy of the paper which has address written on it and ask you to make same changes in A using carbon copy of address.Will you be able to make any changes in original picture A now??? This time answer is YES. Same is the case when the carbon copy of address is passed to a function.

1 comment:

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply