swap

Mar 9, 2013 at 1:07am
Hello..
what is the pb here


#include <iostream>

using namespace std;
void swap(int a, int b)
{
int t;
t=a;
a=b;
b=t;

cout << "x ="<< a <<" & "<< "y ="<< b << endl;
}
int main()
{

int temp;
int x=5,y=10;
cout << "x ="<< x <<" & "<< "y ="<< y << endl;
swap( x, y);

cout << "x ="<< x <<" & "<< "y ="<< y << endl;

return 0;
}

thank you
Mar 9, 2013 at 1:10am
it works with pointers and without void. but that case doesnt work.!!
Mar 9, 2013 at 1:10am
You need to pass by reference.
void swap( int &a, int &b )
Mar 9, 2013 at 1:22am
this works as well.. but why what I wrote is incorrect !!!
Mar 9, 2013 at 1:29am
closed account (3CXz8vqX)
You're using the solution as it is because you can't 'return' two variables from a function, just the one, so you have to pass them around by reference rather than by value (which is more of a copy function).

If you could return two variables...it would look something like this

1
2
3
4
5
int swap ( int x , int y )
{
   return ( int y , int x );  //This isn't possible however. 
}


You MIGHT be able to use a list or an an array to achieve something similar but it's easier and more efficient to just pass by ref.
Mar 9, 2013 at 2:55am
void is not function ... it seems procedure in turbo pascal...
so it can return many values ..I think
Mar 9, 2013 at 2:58am
No, it can't.

void denotes that the function won't return a value.
Topic archived. No new replies allowed.