next up previous
Next: Function Overloading Up: TwelfthWeek Previous: Scope

Argument Passing

When a function is called, arguments are passed by value, meaning that a copy is made and given to the called function. That's why this doesn't do what is intended:
void doubleThis(int i) {
    i *= 2;
    cout << i;
    }

int main() {
    int i = 7;
    doubleThis(i);
    cout << i;	//prints 7
    }
When doubleThis() is called, a copy of its argument - the variable i in main() - is made and passed. The copy is doubled and printed, giving the expected result (14). But once it exits, its copy is destroyed (that's why it's called a local variable - it's local to the function and don't persist once the function returns). Then main() prints its variable i and 7 is printed, because nobody changed its value. If you xerox something and give the copy to a friend, who then scribbles something on it, would you expect the original to change?

If you indeed want the variable in the calling function to change, pass it by reference:

void doubleThis(int &i) {
    i *= 2;
    }
Note the ampersand before the definition of i. This says that you want a reference to the original variable rather than a copy of it. Now doubleThis() works as expected.



cs101 senior TA 2005-10-24