/* EXAMPLE PROGRAM#1: Parameter Passing (refval.cc) * * CS302-11/21 - Spring 96 * * This program demonstrates value parameters vs. reference parameters. * Its sole purpose is to demonstrate the difference between the two. * * This file can be found at * http://www.cs.wisc.edu/~hcl/cs302/refval.cc */ #include // function prototypes void fun1(int& x); int fun2(int y); void fun3(int& x,int& y); void fun4(int& x,int y); void printints(int,int,int); main() { int a=0, b=5, c=10; // Start cout << endl << "In the order: a, b, c. " << endl; printints(a,b,c); fun1(a); // Section 1 fun1(b); fun1(c); printints(a,b,c); cout << " fun2(" << a << ") returns: " << fun2(a) << endl; // Section 2 cout << " fun2(" << b << ") returns: " << fun2(b) << endl; cout << " fun2(" << c << ") returns: " << fun2(c) << endl; cout << " fun2(20) returns: " << fun2(20) << endl; // fun2(20) <=> fun2(a) printints(a,b,c); fun3(a,b); // Section 3 fun3(b,c); printints(a,b,c); fun3(a,b); // Section 4 printints(a,b,c); fun3(b,a); // Section 5 printints(a,b,c); cout << endl << "Switch order: b, c, a. " << endl; // depends on arg order printints(b,c,a); } // main() ends // *** FUNCTION DEFINTIONS BEGIN HERE *** void fun1(int& x) // this is a reference parameter, so whatever happens to x { // will also happen to whatever variable is passed to it. x = x + 20; } int fun2(int y) // this is a value parameter, so an *value* is coming in and { // will be copied into the new, and distinct, location y. y = y + 12; // The function returns the result, but this has no effect return y; // on the calling argument. } void fun3(int& x, int& y) // two reference parameters, so both args are affected back { // in main() x = x / 2; y = y / 3; } void fun4(int& x, int y) // x is a reference parameter, so its argument will change { // back in main(), but y is a value parameter, so its argument x = x + 100; // will not change. y = y + 500; } void printints(int q, int r, int s) { cout << " " << q << ", " << r << ", " << s << endl; }