Source of ptrparam.cpp


  1: // Filename: PTRPARAM.CPP
  2: // Purpose:  To test your knowledge of pointers as parameters.

  4: #include <iostream>
  5: #include <iomanip>
  6: using namespace std;


  9: void DoIt1(int n1, int& n2)
 10: {
 11:     n1 = n1 * 2;
 12:     n2 = n2 + 3;
 13:     cout << setw(3) << n1 << "  " << setw(3) << n2 << endl;
 14: }


 17: void DoIt2(int* p1, int* p2)
 18: {
 19:     *p1 = *p1 * *p1;
 20:     *p2 =  -2 * *p2;
 21:     cout << setw(3) << *p1 << "  " << setw(3) << *p2 << endl;
 22: }


 25: int main()
 26: {
 27:     cout << "\nThis program illustrates pointer (and other) parameters."
 28:          << "\nStudy the source code and the output simultaneously.\n";

 30:     int n1 = 2;
 31:     int n2 = 3;

 33:     int* p1;
 34:     int* p2;
 35:     p1 = new int;
 36:     p2 = new int;
 37:     *p1 = 4;
 38:     *p2 = 5;

 40:     cout << endl;
 41:     cout << setw(3) << n1 << "  " << setw(3) << n2 << endl;
 42:     DoIt1(n1, n2);
 43:     cout << setw(3) << n1 << "  " << setw(3) << n2 << endl << endl;

 45:     cout << setw(3) << *p1 << "  " << setw(3) << *p2 << endl;
 46:     DoIt2(p1, p2);
 47:     cout << setw(3) << *p1 << "  " << setw(3) << *p2 << endl << endl;

 49:     cout << setw(3) << *p1 << "  " << setw(3) << *p2 << endl;
 50:     DoIt1(*p1, *p2);
 51:     cout << setw(3) << *p1 << "  " << setw(3) << *p2 << endl << endl;

 53:     cout << setw(3) << n1 << "  " << setw(3) << n2 << endl;
 54:     DoIt2(&n1, &n2);
 55:     cout << setw(3) << n1 << "  " << setw(3) << n2 << endl;

 57:     return 0;
 58: }