How do you write a function swap?
How do you write a function swap?
you can use follwing code:
#include<stdio.h>
#include<conio.h>
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
printf("a=%d b=%d",*a,*b);
}
void main()
{
int a=5,b=8;
swap(&a,&b);
}
Well, Swetha's method is proper, but only meant for integers.
Following is the swap function for any type like: int, char, structure, pointers etc. anything.
template<class T>
void swap(T &data1, T &data2)
{
T temp = data1;
data1 = data2;
data2 = temp;
}
fine...you can use a single statement to swap two numbers without the use of temporary variable...
a^=b^=a^=b
regards rms...
No, 1st of all, it's just an illusion that you don't use temporary. When u do a ^= b, the XOR of 2 variables is indeed stored in Accumulator (which is a temporary). So, this operation will be slower (swap result into accumulator and then accumulator back to the variable 'a').
2nd thing is, you can't swap structures or complex data types with this method.
ya,correct,its for integer variables only...But we dont use temporary varibles explicitly...
Try with the followings.
Code:main() { int a=10; int b=20; printf("a = %d\nb = %d\n",a,b); a =a+b; b=a-b; a=a-b; // This is first way. a =a*b; b=a/b; a=a/b; printf("a = %d\nb = %d\n",a,b); }Code:main() { int a=10; int b=20; printf("a = %d\nb = %d\n",a,b); a =a*b; b=a/b; a=a/b; //This is second way printf("a = %d\nb = %d\n",a,b); }
Hi,The second way will not work properly when the variables a or b equal to zero,another one problem is that if "a*b" exceeds integer range, it will give unexpected results.
/*Usin call by value parameter*/
void swap(int a,int b)
{
int c=a;
a=b;
b=c;
printf("After swap : a = %d, b = %d\n",a,b);
}
/*Usin call by reference*/
void swap_a(int &a, int &b)
{
int temp = *a;
*a =*b;
*b = temp;
}
/*Usin reference parameter*/
void swap_b(int &a,int &b)
{
int c = a;
a= b;
b= c;
}
void main()
{
int a =5,b=6;
swap(a,b);
swap_a(&a,&b);
printf("After swap : a = %d, b = %d\n",a,b);
swap_b(a,b);
printf("After swap : a = %d, b = %d\n",a,b);
}
What language, and what are you trying to swap?
In C++ it's easy:
Since C doesn't provide built-in support for generics, you either have to write separate functions for each data type, or you need to muck with void pointers (not recommended).Code:template <typename T> void swap(T& a, T& b) { T tmp = a; a = b; b = tmp; }