confuse about a test programme

first of all my english is poor, i hope i make my question clear.
i wrote a test programe
but i cant explain why it can get a right answer.

#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
// & v1 stands for address
// same time v1 is the same as &v1

void swap(int * &v1, int * &v2){

int *temp = v2;
v2 = v1;
v1 = temp;
}


int main(){

int x = 9 , y = 6 ;

//int * p = &x;
//int * q = &y;
swap(x, y );

cout << x<<y <<endl;
system("PAUSE");

}


my questions are: what kinds parameters should this swap function take ?
i thought it should be pointers, but why it can take integers?
If you are trying to swap int's and not int*'s then try taking references to int's (int&) as your parameters.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//this function takes 2 int's as parameters (passed by reference)
void swap(int &a, int &b) {
  int temp = b;
  b = a;
  a = temp;
}

int main() {
  int x = 9, y = 6;
  swap(x, y);
  cout << x << ", " << y << endl;
  //system("pause");
  return 0;
}
6, 9
use google translate and write in your language (just a tip for the future).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void swap(int * &v1, int * &v2){

int temp = *v2;//this takes the value from v2 not its address as you mistakenly did. 
*v2 = *v1; //* means we are working with the value it self, not the address
*v1 = temp; 
}


int main(){

int x = 9 , y = 6 ;

//int * p = &x;
//int * q = &y;
swap(x, y );

cout << x<<y <<endl;
system("PAUSE");

} 
Topic archived. No new replies allowed.