swaps.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // swaps.cpp -- swapping with references and with pointers
  2. #include <iostream>
  3. void swapr(int & a, int & b); // a, b are aliases for ints
  4. void swapp(int * p, int * q); // p, q are addresses of ints
  5. void swapv(int a, int b); // a, b are new variables
  6. int main()
  7. {
  8. using namespace std;
  9. int wallet1 = 300;
  10. int wallet2 = 350;
  11. cout << "wallet1 = $" << wallet1;
  12. cout << " wallet2 = $" << wallet2 << endl;
  13. cout << "Using references to swap contents:\n";
  14. swapr(wallet1, wallet2); // pass variables
  15. cout << "wallet1 = $" << wallet1;
  16. cout << " wallet2 = $" << wallet2 << endl;
  17. cout << "Using pointers to swap contents again:\n";
  18. swapp(&wallet1, &wallet2); // pass addresses of variables
  19. cout << "wallet1 = $" << wallet1;
  20. cout << " wallet2 = $" << wallet2 << endl;
  21. cout << "Trying to use passing by value:\n";
  22. swapv(wallet1, wallet2); // pass values of variables
  23. cout << "wallet1 = $" << wallet1;
  24. cout << " wallet2 = $" << wallet2 << endl;
  25. // cin.get();
  26. return 0;
  27. }
  28. void swapr(int & a, int & b) // use references
  29. {
  30. int temp;
  31. temp = a; // use a, b for values of variables
  32. a = b;
  33. b = temp;
  34. }
  35. void swapp(int * p, int * q) // use pointers
  36. {
  37. int temp;
  38. temp = *p; // use *p, *q for values of variables
  39. *p = *q;
  40. *q = temp;
  41. }
  42. void swapv(int a, int b) // try using values
  43. {
  44. int temp;
  45. temp = a; // use a, b for values of variables
  46. a = b;
  47. b = temp;
  48. }