Use reference parameters to create the swap() function. : reference parameter « Function « C++ Tutorial






#include <iostream> 
using namespace std; 
 
void swap(int &x, int &y); 
 
int main() 
{ 
  int i, j; 
 
  i = 10; 
  j = 20; 
 
  cout << "Initial values of i and j: "; 
  cout << i << ' ' << j << '\n'; 
 
  swap(j, i); 
 
  cout << "Swapped values of i and j: "; 
  cout << i << ' ' << j << '\n'; 
 
  return 0; 
} 
 
void swap(int &x, int &y) 
{ 
  int temp; 
 
  temp = x;  
  x = y;     
  y = temp;  
}
Initial values of i and j: 10 20
Swapped values of i and j: 20 10








7.4.reference parameter
7.4.1.Using a reference parameter.
7.4.2.Use reference parameters to create the swap() function.
7.4.3.Pass by reference by using pointer
7.4.4.Pass by reference using references
7.4.5.Returning multiple values from a function using references
7.4.6.Passing references to objects