lect5_3

lect5_3 - Argument Passing by Reference 1 Programmer...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Argument Passing by Reference 1 Programmer Defined Functions - Part 3 Argument Passing by Reference So far in our example programs, when a function call is made, even if a variable is supplied as an argument, the function takes only the value of the variable and does not change the variable in any way. That is, the function takes a copy of the value of the actual argument. This way of supplying arguments to a function is referred to as passed by value . We have seen that, using the pass by value method, a function can work only on copies of arguments, not on the actual arguments themselves. Thus, the actual arguments have the same value before and after the function call. For example recall the following program. #include <iostream> using namespace std; int changeValue(int); // function declaration // changes x value as x = x+10 and prints the new value of x int main() { int x = 40; cout << "Value of x in main before function call = " << x << endl; int y = changeValue(x); cout << "Value of x in main after return from function = " << x << endl; return 0; } // end function main // function definition int changeValue(int x) { // function header x = x + 10; cout << "Value of x after x = x+10 in the function = " << x << endl; return x; } // end function changeValue Output of the above program. Value of x in main before function call = 40 Value of x after x = x+10 in the function = 50 Value of x in main after return from function = 40 Argument Passing by Reference 2 Can we change the value of the argument itself (not a copy of the argument) inside a function? The answer is yes ; using a different method of passing arguments, but not using the pass by value method. We can modify the argument variable supplied to the calling function using a method known as the pass by reference method. Using this method, we can pass (supply) the variable itself (not a copy of its value) to the function. Then any changes that are made to this variable will be in affect in the calling program as well....
View Full Document

Page1 / 8

lect5_3 - Argument Passing by Reference 1 Programmer...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online