home *** CD-ROM | disk | FTP | other *** search
/ Beginning C++ Through Gam…rogramming (2nd Edition) / BCGP2E.ISO / source / chapter07 / swap_pointer_ver.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2004-04-11  |  1.1 KB  |  49 lines

  1. // Swap Pointer
  2. // Demonstrates passing constant pointers to alter argument variables
  3.  
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. void badSwap(int x, int y);
  9. void goodSwap(int* const pX, int* const pY);
  10.  
  11. int main()
  12. {
  13.     int myScore = 150;
  14.     int yourScore = 1000;
  15.     cout << "Original values\n";
  16.     cout << "myScore: " << myScore << "\n";
  17.     cout << "yourScore: " << yourScore << "\n\n";
  18.     
  19.     cout << "Calling badSwap()\n";
  20.     badSwap(myScore, yourScore);
  21.     cout << "myScore: " << myScore << "\n";
  22.     cout << "yourScore: " << yourScore << "\n\n";
  23.         
  24.     cout << "Calling goodSwap()\n";
  25.     goodSwap(&myScore, &yourScore);
  26.     cout << "myScore: " << myScore << "\n";
  27.     cout << "yourScore: " << yourScore << "\n";
  28.  
  29.     return 0;
  30. }
  31.  
  32. void badSwap(int x, int y)
  33. {
  34.     int temp = x;
  35.     x = y;
  36.     y = temp;
  37. }
  38.  
  39. void goodSwap(int* const pX, int* const pY)    
  40. {
  41.     //store value pointed to by pX in temp
  42.     int temp = *pX;
  43.     //store value pointed to by pY in address pointed to by pX
  44.     *pX = *pY;
  45.     //store value originally pointed to by pX in address pointed to by pY       
  46.     *pY = temp;      
  47. }
  48.  
  49.