#include using namespace std; /** * Ethan Schreiber * CS31 * October 23, 2008 * * This file illustrates the concept of pass by reference vs. pass by value. * * By default, variables are pass by value. This means that a copy of the * variable is made and passed to the function. If you modify this variable * within the function, the changes will not escape the function. * * If you put an & between the parameter type and the parameter name * (i.e. int &x), then the parameter is pass by reference. This means that * if you modify the parameter within the function, changes will be made to * the variable passed into the function. * * Please see Chapter 4 (pg. 134) for a much more in depths discussion of this. */ void intFoo(int, int&); void stringFoo(string, string&); int main() { // ************************************************ // * First show pass by value/reference with ints * // ************************************************ int int1 = 100; int int2 = 100; cout << endl << "Before Function Call" << endl << " value : " << int1 << endl << " reference: " << int2 << endl << endl; // notice we don't do anything special here, we call this function // normally intFoo(int1,int2); cout << "After Function Call" << endl << " value : " << int1 << endl << " reference: " << int2 << endl << endl; // ************************************************** // * Now show pass by value/reference withs strings * // ************************************************** string string1 = string("string"); string string2 = string("string"); cout << endl << "Before Function Call" << endl << " value : " << string1 << endl << " reference: " << string2 << endl << endl; // notice we don't do anything special here, we call this function // normally stringFoo(string1, string2); cout << "After Function Call" << endl << " value : " << string1 << endl << " reference: " << string2 << endl << endl; } /** * Illustrates pass by reference with ints. * notice the the first parameter is pass by value since * it has no & and the 2nd parameter is pass by reference since it * does have an &. */ void intFoo(int firstInt, int &secondInt) { firstInt = 50; secondInt = 50; } void stringFoo(string firstString, string &secondString) { firstString = string("new string"); secondString = string("new string"); }