C++ Function Parameter reference parameter to swap parameter's value

Description

C++ Function Parameter reference parameter to swap parameter's value

#include <iostream>
using namespace std;
void swap(double&, double&);  // function receives two references
int main()// w w  w.j  a  v  a 2  s  .c o  m
{
   double firstnum = 20.5, secnum = 6.25;
   cout << "The value stored in firstnum is: " << firstnum << endl;
   cout << "The value stored in secnum is: " << secnum << "\n\n";
   swap(firstnum, secnum);     // call the function with references
   cout << "The value stored in firstnum is now: " << firstnum << endl;
   cout << "The value stored in secnum is now: " << secnum << endl;
   return 0;
}
void swap(double& num1, double& num2)
{
   double temp;
   temp = num1;   // save num1's value
   num1 = num2;   // store num2's value in num1
   num2 = temp;   // change num2's value
   return;
}



PreviousNext

Related