Practice examples: reference parameters

Remember that passing a parameter by reference is done by preceeding the parameter name with the & symbol in the parameter list, e.g.
void swap(int &x, int &y)

The effect of doing this is to allow the function to modify the value of the variable passed by reference.

Exercise: study the four different swap routines shown below, predict the output that will result, and run the program to check your predictions. Make sure you understand how/why the results are what they are.
#include <cstdio>

void swap1(int x, int y);
void swap2(int &x, int y);
void swap3(int x, int &y);
void swap4(int &x, int &y);

int main()
{
   int a, b;

   // try swap1
   a = 1; b = 2; swap1(a, b);
   printf("swap1(1,2) gives a=%d, b=%d\n", a, b);

   // try swap2
   a = 1; b = 2; swap2(a, b);
   printf("swap2(1,2) gives a=%d, b=%d\n", a, b);

   // try swap3
   a = 1; b = 2; swap3(a, b);
   printf("swap3(1,2) gives a=%d, b=%d\n", a, b);

   // try swap4
   a = 1; b = 2; swap4(a, b);
   printf("swap4(1,2) gives a=%d, b=%d\n", a, b);

}

void swap1(int x, int y)
{
   int tmp = x;
   x = y;
   y = tmp;
}

void swap2(int &x, int y)
{
   int tmp = x;
   x = y;
   y = tmp;
}

void swap3(int x, int &y)
{
   int tmp = x;
   x = y;
   y = tmp;
}

void swap4(int &x, int &y)
{
   int tmp = x;
   x = y;
   y = tmp;
}
#include <iostream>
using namespace std;

void swap1(int x, int y);
void swap2(int &x, int y);
void swap3(int x, int &y);
void swap4(int &x, int &y);

int main()
{
   int a, b;

   // try swap1
   a = 1; b = 2; swap1(a, b);
   cout << "swap1(1,2) gives a=" << a << ", b=" << b << endl;

   // try swap2
   a = 1; b = 2; swap2(a, b);
   cout << "swap2(1,2) gives a=" << a << ", b=" << b << endl;

   // try swap3
   a = 1; b = 2; swap3(a, b);
   cout << "swap3(1,2) gives a=" << a << ", b=" << b << endl;

   // try swap4
   a = 1; b = 2; swap4(a, b);
   cout << "swap4(1,2) gives a=" << a << ", b=" << b << endl;

}

void swap1(int x, int y)
{
   int tmp = x;
   x = y;
   y = tmp;
}

void swap2(int &x, int y)
{
   int tmp = x;
   x = y;
   y = tmp;
}

void swap3(int x, int &y)
{
   int tmp = x;
   x = y;
   y = tmp;
}

void swap4(int &x, int &y)
{
   int tmp = x;
   x = y;
   y = tmp;
}