Paul Herring wrote:
> On Dec 21, 2007 6:55 AM, p.angel88 <[EMAIL PROTECTED]> wrote:
>> hi to all
>> follows a program for call by value
>> *********************************************************************
>> #include<stdio.h>
>> #include<conio.h>
>> void swap(int,int);
> 
> void swap(int*, int*)
> 
>> void main()
>> {
>> int a,b;
>> clrscr();
>> printf("enter two values");
>> scanf("%d%d",&a,&b);
>> printf("value before swapping a=%d & b=&d",a,b);
>> swap(a,b);
> 
> swap(&a, &b);
> 
>> printf("value after swapping a=%d & b=%d",a,b);
>> getch();
>> }
>> void swap(int x,int y)
>> {
>> int t;
>> t=x;
>> x=y;
>> y=t;
>> }
> 
>  void swap(int* x,int* y)
>  {
>  int t;
>  t=*x;
>  *x=*y;
>  *y=t;
>  }
> 
>> ********************************************************************
>> swapping is interchange of value
>> if we assign a=5 & b=2 the output should be a=2 & b=5.
>> but the output is coming same as input. so what is the mistake in
>> program?
> 
> You were modifying copies of a and b, not the original a&b's.

An easier way to swap two variables is to use a function template in C++:

template <class T>
inline void swap(T &x, T &y)
{
   T temp(x);
   x = y;
   y = temp;
}

Then, to use it, just do:

swap(a, b);


That has four advantages over any C implementation:

1)  No messy pointer operations to deal with.  The compiler handles all 
that behind the scenes all thanks to the "pass by address" feature of C++.

2)  It is easier to read and also easier to maintain.  Write once, never 
worry about again.

3)  It is generic and supports pretty much anything (int, float, double, 
etc.) including other classes and templates.  NOTE:  It won't properly 
handle two different classes that have the same base class.  You'd have 
to use clone()-enabled smart pointers of the base class to protect the 
derived  objects from getting hosed.

4)  It will probably be inlined by the compiler, which means it will be 
faster than any equivalent function in C (not that it really matters in 
this particular case).


Four more reasons to switch to C++.

-- 
Thomas Hruska
CubicleSoft President
Ph: 517-803-4197

*NEW* MyTaskFocus 1.1
Get on task.  Stay on task.

http://www.CubicleSoft.com/MyTaskFocus/

Reply via email to