A function that swaps any two integers passed to it using reference - C++ Data Type

C++ examples for Data Type:Reference

Description

A function that swaps any two integers passed to it using reference

Demo Code

#include <iostream>
using namespace std;
void swap_them(int &num1, int &num2);
void main()//from  ww w  . ja  v a2  s . c  o  m
{
   int i=10, j=20;
   cout << "\n\nBefore swap, i is " << i << " and j is " << j << "\n\n";
   swap_them(i, j);
   cout << "\n\nAfter swap, i is " << i << " and j is " << j << "\n\n";
   return;
}
void swap_them(int &num1, int &num2)
{
   int temp;           // Variable that holds in-between swapped value.
   temp = num1;        // The calling function's variables
   num1 = num2;        // (and not copies of them) are
   num2 = temp;        // changed in this function.
   return;
}

Result


Related Tutorials